我想提取一个字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的?
例子:
line = "hello 12 hi 89"
结果:
[12, 89]
我想提取一个字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的?
例子:
line = "hello 12 hi 89"
结果:
[12, 89]
当前回答
我只是添加这个答案,因为没有人添加一个使用异常处理,因为这也适用于浮动
a = []
line = "abcd 1234 efgh 56.78 ij"
for word in line.split():
try:
a.append(float(word))
except ValueError:
pass
print(a)
输出:
[1234.0, 56.78]
其他回答
使用下面的正则表达式是一种方法
lines = "hello 12 hi 89"
import re
output = []
#repl_str = re.compile('\d+.?\d*')
repl_str = re.compile('^\d+$')
#t = r'\d+.?\d*'
line = lines.split()
for word in line:
match = re.search(repl_str, word)
if match:
output.append(float(match.group()))
print (output)
和findall Re.findall (r'\d+', "hello 12 hi 89")
['12', '89']
re.findall(r'\b\d+\b', "hello 12 hi 89 33F AC 777")
['12', '89', '777']
@jmnas,我喜欢你的答案,但它没有找到浮动。我正在编写一个脚本来解析前往CNC铣床的代码,需要找到可以是整数或浮点数的X和Y维度,所以我将您的代码改编为以下内容。这就找到了int, float值为正和负。仍然没有找到十六进制格式的值,但你可以添加“x”和“A”通过“F”到num_char元组,我认为它会解析像“0x23AC”这样的东西。
s = 'hello X42 I\'m a Y-32.35 string Z30'
xy = ("X", "Y")
num_char = (".", "+", "-")
l = []
tokens = s.split()
for token in tokens:
if token.startswith(xy):
num = ""
for char in token:
# print(char)
if char.isdigit() or (char in num_char):
num = num + char
try:
l.append(float(num))
except ValueError:
pass
print(l)
我找到的最佳选择如下。它将提取一个数字,并可以消除任何类型的字符。
def extract_nbr(input_str):
if input_str is None or input_str == '':
return 0
out_number = ''
for ele in input_str:
if ele.isdigit():
out_number += ele
return float(out_number)
我只是添加这个答案,因为没有人添加一个使用异常处理,因为这也适用于浮动
a = []
line = "abcd 1234 efgh 56.78 ij"
for word in line.split():
try:
a.append(float(word))
except ValueError:
pass
print(a)
输出:
[1234.0, 56.78]
我发现的最干净的方法是:
>>> data = 'hs122 125 &55,58, 25'
>>> new_data = ''.join((ch if ch in '0123456789.-e' else ' ') for ch in data)
>>> numbers = [i for i in new_data.split()]
>>> print(numbers)
['122', '125', '55', '58', '25']
或:
>>> import re
>>> data = 'hs122 125 &55,58, 25'
>>> numbers = re.findall(r'\d+', data)
>>> print(numbers)
['122', '125', '55', '58', '25']