我有一个包含文字和文字的文件。数字 我希望找到这些数字然后求和 我写的是:
import re
fhand = open('ReSample.txt')
for line in fhand:
y = re.findall('[0-9]+', line)
for item in y:
item = int(item)
total = total + item
print total
错误是未定义的总数!!!
文件行示例
编写程序(或编程)是非常有创意和有益的 活动。您可以编写3036个程序,原因很多 致力于解决7209难以解决的数据分析问题 乐于帮助
Desired output >>> 3036 + 7209 + ......
您可以在没有重大更改的情况下修复我的代码吗?
提前致谢..
答案 0 :(得分:0)
您正尝试使用变量total
向其添加item
并将总和分配给total
。通过第一次执行循环,total
不会被定义。
请考虑这种方法:
import re
fhand = open('ReSample.txt')
total=0
for line in fhand:
y = re.findall('[0-9]+', line)
for item in y:
item = int(item)
total = total + item
print(total)
输出为10245
。