用python提取文档内全部数字并求和

2025-06-27 16:33:55
推荐回答(3个)
回答1:

因为不知道 "sample.txt" 的内容是什么格式,我猜是这样的问题:

stuff = re.findall ('[0-9]+',line)

的意思是将字符串 line 中的所有连续的数字找到,组成数组

当 line 中的内容存在不止一个数字的时候,例如:

123 234

时,stuff 的结果为:

['123', '234']

这样的数组,长度不为 1

这时,语句

if len(stuff) != 1 :continue

就会跳过这一循环,使得这行中的数字没有被加到总和中。


如果是这样的话,例子代码:

import re
digits_reg = re.compile(r'\d+')

with open('sample.txt', 'r') as file_handle:
    print sum(sum(map(int, digits_reg.findall(line))) for line in file_handle)

 

ps:

我猜你的语句

if len(stuff) != 1 :continue

是想要跳过没有数字的行,但是没有考虑多个数字的行,所以少加了

回答2:

你这样只取到了每一行的第一组数字,并且只在它是一位数时才会被计算。

既然使用re,就不需要一行行去处理了,也不需要去空格了,只需要取出数字处理就好。

import re
nums = []
with open('_sumfile.txt', 'r') as f:
    for s in re.findall(r'\d+', f.read()):
        nums.append(float(s))
print(sum(nums))

_sumfile.txt的内容:

this is a test file.
3
5
can use 100?
over.

返回108.0

回答3:

if len(stuff) != 1 :continue
是什么意思?放在这里起什么作用?