问题是读取文件,使用 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
OUTPUT:
您需要将查找结果附加到另一个列表。这样当迭代到下一行时,在当前行找到的数字将被保留。
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
or
with open('sample.txt') as f:
print sum(map(int, re.findall(r'\d+', f.read())))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)