我想提取一个字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的?
例子:
line = "hello 12 hi 89"
结果:
[12, 89]
我想提取一个字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的?
例子:
line = "hello 12 hi 89"
结果:
[12, 89]
当前回答
因为这些都不是我需要找到的excel和word文档中处理真实世界的财务数据,这里是我的变体。它处理整数、浮点数、负数、货币数(因为它在分割时不回复),并且可以选择删除小数部分而只返回整数,或者返回所有内容。
它还处理印度湖的数字系统,其中逗号出现不规则,而不是每3个数字分开。
它不处理科学符号或预算中括号内的负数——将显示为正数。
它也不提取日期。在字符串中查找日期有更好的方法。
import re
def find_numbers(string, ints=True):
numexp = re.compile(r'[-]?\d[\d,]*[\.]?[\d{2}]*') #optional - in front
numbers = numexp.findall(string)
numbers = [x.replace(',','') for x in numbers]
if ints is True:
return [int(x.replace(',','').split('.')[0]) for x in numbers]
else:
return numbers
其他回答
我只是添加这个答案,因为没有人添加一个使用异常处理,因为这也适用于浮动
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]
如果你只想提取正整数,试试下面的方法:
>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in txt.split() if s.isdigit()]
[23, 11, 2]
我认为这比正则表达式示例更好,因为您不需要另一个模块,而且它更具可读性,因为您不需要解析(和学习)正则表达式迷你语言。
这将不识别浮点数、负整数或十六进制格式的整数。如果您不能接受这些限制,下面jmnas的答案可以解决问题。
line2 = "hello 12 hi 89" # this is the given string
temp1 = re.findall(r'\d+', line2) # find number of digits through regular expression
res2 = list(map(int, temp1))
print(res2)
可以使用findall表达式通过digit搜索字符串中的所有整数。
在第二步中,创建一个列表res2,并将string中找到的数字添加到该列表中。
@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)
我很惊讶地发现还没有人提到itertools的用法。Groupby作为实现这一目标的替代方案。
你可以使用itertools.groupby()和str.isdigit()来从字符串中提取数字,如下:
from itertools import groupby
my_str = "hello 12 hi 89"
l = [int(''.join(i)) for is_digit, i in groupby(my_str, str.isdigit) if is_digit]
由l保持的值将是:
[12, 89]
PS:这只是为了说明,作为一种替代方案,我们也可以使用groupby来实现这一点。但这不是一个推荐的解决方案。如果您想实现这一点,您应该使用基于使用str.isdigit作为过滤器的列表理解的fmark的接受答案。