问题是读取文件,使用 re.findall() 查找整数,查找 '[0-9]+' 的正则表达式,然后将提取的字符串转换为整数并对整数求和。
我的代码:其中sample.txt是我的文本文件
import re
hand = open('sample.txt')
for line in hand:
line = line.rstrip()
x = re.findall('[0-9]+',line)
print x
x = [int(i) for i in x]
add = sum(x)
print add
输出:
请您参考如下方法:
您需要将查找结果附加到另一个列表。这样当迭代到下一行时,在当前行找到的数字将被保留。
import re
hand = open('sample.txt')
l = []
for line in hand:
x = re.findall('[0-9]+',line)
l.extend(x)
j = [int(i) for i in l]
add = sum(j)
print add
或
with open('sample.txt') as f:
print sum(map(int, re.findall(r'\d+', f.read())))
