如何在Python中从字符串中提取数字?
我将提取字符串中包含的所有数字。正则表达式和如何在Python中从字符串中提取数字?,python,regex,string,numbers,Python,Regex,String,Numbers,我将提取字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的 例如: line = "hello 12 hi 89" 结果: [12, 89] 我会使用regexp: >>> import re >>> re.findall(r'\d+', 'hello 42 I\'m a 32 string 30') ['42', '32', '30'] 这也将与bla42bla中的42匹配。如果只希望数字由单词边界(空格、句点、逗号)分隔,可
isdigit()
方法哪个更适合这个目的
例如:
line = "hello 12 hi 89"
结果:
[12, 89]
我会使用regexp:
>>> import re
>>> re.findall(r'\d+', 'hello 42 I\'m a 32 string 30')
['42', '32', '30']
这也将与bla42bla
中的42匹配。如果只希望数字由单词边界(空格、句点、逗号)分隔,可以使用\b:
>>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')
['42', '32', '30']
要以数字列表而不是字符串列表结束,请执行以下操作:
>>> [int(s) for s in re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')]
[42, 32, 30]
我假设你想要的不仅仅是整数,而是浮点数,所以我会这样做:
l = []
for t in s.split():
try:
l.append(float(t))
except ValueError:
pass
请注意,此处发布的一些其他解决方案不适用于负数:
>>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string -30')
['42', '32', '30']
>>> '-3'.isdigit()
False
如果只想提取正整数,请尝试以下操作:
>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in txt.split() if s.isdigit()]
[23, 11, 2]
我认为这比regex示例更好,因为您不需要另一个模块,而且它更可读,因为您不需要解析(和学习)这个模块
这将无法识别浮点数、负整数或十六进制格式的整数。如果你不能接受这些限制,我会做的。@jmnas,我喜欢你的答案,但没有找到浮动。我正在编写一个脚本来解析要去CNC工厂的代码,需要找到可以是整数或浮点数的X和Y维度,因此我将您的代码改编为以下内容。这将查找int、float和正负VAL。仍然找不到十六进制格式的值,但您可以将“x”和“A”通过“F”添加到
num\u 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)
这已经有点晚了,但是您也可以扩展正则表达式来解释科学符号
import re
# Format is [(<string>, <expected output>), ...]
ss = [("apple-12.34 ba33na fanc-14.23e-2yapple+45e5+67.56E+3",
['-12.34', '33', '-14.23e-2', '+45e5', '+67.56E+3']),
('hello X42 I\'m a Y-32.35 string Z30',
['42', '-32.35', '30']),
('he33llo 42 I\'m a 32 string -30',
['33', '42', '32', '-30']),
('h3110 23 cat 444.4 rabbit 11 2 dog',
['3110', '23', '444.4', '11', '2']),
('hello 12 hi 89',
['12', '89']),
('4',
['4']),
('I like 74,600 commas not,500',
['74,600', '500']),
('I like bad math 1+2=.001',
['1', '+2', '.001'])]
for s, r in ss:
rr = re.findall("[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?", s)
if rr == r:
print('GOOD')
else:
print('WRONG', rr, 'should be', r)
重新导入
#格式为[(,),…]
ss=[(“苹果-12.34 ba33na fanc-14.23e-2yapple+45e5+67.56E+3”,
[12.34',33',14.23e-2',+45e5',+67.56E+3'],
(“你好X42我是Y-32.35字符串Z30”,
['42', '-32.35', '30']),
('he33llo 42 I'm a 32 string-30',
['33', '42', '32', '-30']),
(‘h3110 23猫444.4兔11 2狗’,
['3110', '23', '444.4', '11', '2']),
(“你好12嗨89”,
['12', '89']),
('4',
['4']),
(‘我喜欢74600个逗号,而不是500’,
['74,600', '500']),
(‘我喜欢糟糕的数学1+2=.001’,
['1', '+2', '.001'])]
对于ss中的s,r:
rr=re.findall(“[-+]?[.]?[\d]+(?:,\d\d)*[\.]?\d*(?:[eE][-+]?\d+”,s)
如果rr==r:
打印(“好”)
其他:
打印('error',rr',should be',r)
一切都好
此外,您可以查看下面是我找到的最佳选项。它将提取一个数字,并可以消除任何类型的字符
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)
这个答案还包含数字在字符串中浮动的情况
def get_first_nbr_from_str(input_str):
'''
:param input_str: strings that contains digit and words
:return: the number extracted from the input_str
demo:
'ab324.23.123xyz': 324.23
'.5abc44': 0.5
'''
if not input_str and not isinstance(input_str, str):
return 0
out_number = ''
for ele in input_str:
if (ele == '.' and '.' not in out_number) or ele.isdigit():
out_number += ele
elif out_number:
break
return float(out_number)
如果您知道字符串中只有一个数字,即
'hello 12 hi'
,您可以尝试筛选
例如:
In [1]: int(''.join(filter(str.isdigit, '200 grams')))
Out[1]: 200
In [2]: int(''.join(filter(str.isdigit, 'Counters: 55')))
Out[2]: 55
In [3]: int(''.join(filter(str.isdigit, 'more than 23 times')))
Out[3]: 23
但是要小心!!!:
In [4]: int(''.join(filter(str.isdigit, '200 grams 5')))
Out[4]: 2005
我很惊讶地看到,还没有人提到使用的作为替代来实现这一点
您可以使用随从字符串中提取数字,如下所示:
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作为过滤器。由于这些方法都没有处理我需要查找的excel和word文档中的真实财务数字,因此下面是我的变体。它处理整数、浮点数、负数、货币数(因为它不会在拆分时回复),并且可以选择删除小数部分,只返回整数,或者返回所有内容
它还处理印度Laks数字系统,其中逗号不规则出现,而不是每隔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
我一直在寻找一种方法来去除字符串的掩码,特别是从巴西的电话号码中,这篇帖子没有得到回复,但给了我灵感。这是我的解决方案:
>>> phone_number = '+55(11)8715-9877'
>>> ''.join([n for n in phone_number if n.isdigit()])
'551187159877'
使用下面的正则表达式就是一种方法
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)
和芬德尔
re.findall(r'\d+,“你好,12点89”)
re.findall(r'\b\d+\b',“hello 12 hi 89 33F AC 777”)
我只是添加了这个答案,因为没有人使用异常处理添加了一个,而且这也适用于浮动
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]
嗨
您可以使用findall表达式通过数字搜索字符串中的所有整数
在第二步中,创建一个列表res2,并将字符串中的数字添加到此列表中
希望这有帮助
问候,,
Diwakar Sharma要捕获不同的模式,使用不同的模式进行查询很有帮助
设置捕获不同数量感兴趣模式的所有模式:
(查找逗号)12300或12300.00
“[\d]+[,\d]+”
(查找浮动)0.123或.123
'[\d]*[.][\d]+'
(查找整数)123
“[\d]+”
与管道(|)组合成一个具有多个或多个条件的模式。
(注意:首先放置复杂模式,否则简单模式将返回复杂捕获的块,而不是返回完整捕获的复杂捕获)
下面,我们将用re.search()
确认存在一个模式,然后返回一个可编辑的捕获列表。最后,我们将使用括号表示法打印每个catch,以从match对象中再选择match对象返回值
s = 'he33llo 42 I\'m a 32 string 30 444.4 12,001'
if re.search(p, s) is not None:
for catch in re.finditer(p, s):
print(catch[0]) # catch is a match object
返回:
33
42
32
30
444.4
12,001
对于电话号码,您可以简单地排除正则表达式中带有\D
的所有非数字字符:
重新导入
电话号码=“(619)459-3635”
电话号码=re.sub(r“\D”,“电话号码”)
打印(电话号码)
r“\D”
中的r
代表原始字符串。这是必要的。如果没有它,Python将考虑<代码> \d>代码>作为ESC。
[1234.0, 56.78]
line2 = "hello 12 hi 89"
temp1 = re.findall(r'\d+', line2) # through regular expression
res2 = list(map(int, temp1))
print(res2)
p = '[\d]+[.,\d]+|[\d]*[.][\d]+|[\d]+'
s = 'he33llo 42 I\'m a 32 string 30 444.4 12,001'
if re.search(p, s) is not None:
for catch in re.finditer(p, s):
print(catch[0]) # catch is a match object
33
42
32
30
444.4
12,001