所以我有一个文本文件,其中有一些行,如下所示:
“这是 10 条左右 4 条通用文本。
4 内容并不重要 5 它说什么 1
我只是用它,
让 2 成为 2 点。”
我正在尝试使用 re.findall 查找分散在文本中的数字的总和。到目前为止我已经:
import re
handle=open('.txt')
for line in handle:
num = re.findall('[0-9]+', line)
if len(num)>0:
num = list(map(int, num))
total = sum(num)
这就是我所能得到的。使用 re.findall 为 num 分配一系列字符串整数列表 (['10', '4'], ['4', '5', '1'], [], ['2', '2'] )。 Len 过滤掉不包含数字的行(['10', '4'], ['4', '5', '1'], ['2', '2'])。 List(map()) 将列表从字符串转换为整数 ([10, 4], [4, 5, 1], [2, 2]),并将 sum(num) 分配给每个列表的总和 ([14] ,[10],[4])。从这里我试图将这三个数字相加。我想我正在寻找的是 sum(total(sum(num))) 但 Python 不喜欢这样。任何帮助将不胜感激。
最佳答案
您不必在每一行都应用正则表达式:
In [1]: import re
In [2]: txt = """This is 10 some 4 generic text.
...: ...:
...: ...: It doesn't 4 matter 5 what it says 1
...: ...:
...: ...: I'm just using it,
...: ...:
...: ...: To make 2 a 2 point."""
In [3]: sum(map(int, re.findall(r"\d+", txt)))
Out[3]: 28
因此对于文本文件,这应该有效:
import re
with open("input.txt", "r") as handle:
print(sum(map(int, re.findall(r"\d+", handle.read()))))
关于python - 使用 Python 正则表达式对整个文本中随机放置的整数求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54015798/