问题是读取文件,使用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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
要么
with open('sample.txt') as f:
print sum(map(int, re.findall(r'\d+', f.read())))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
791 次 |
| 最近记录: |