我想提取一个字符串中包含的所有数字。正则表达式和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']
我将使用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
因为这些都不是我需要找到的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
str1 = "There are 2 apples for 4 persons"
# printing original string
print("The original string : " + str1) # The original string : There are 2 apples for 4 persons
# using List comprehension + isdigit() +split()
# getting numbers from string
res = [int(i) for i in str1.split() if i.isdigit()]
print("The numbers list is : " + str(res)) # The numbers list is : [2, 4]