如何在Python中对正则表达式匹配结果进行求和

0 投票
2 回答
2406 浏览
提问于 2025-04-18 00:48

我正在尝试从多个文件中提取一些特定的数字,并对这些提取出来的数字进行求和。以下是我到目前为止写的代码。

import re, os
path = "F:/s"
in_files = os.listdir(path)

for g in in_files:
    file = os.path.join(path, g)
    text = open(file, "r")
    a = text.readlines()
    b = a[6]
    m = re.search('\t(.+?)\n', b)
    if m:
        found = m.group()
        print (found)

提取功能正常,我得到了这样的结果。

122
74
97

现在我想把这些数字加起来。

2 个回答

1

我们来用 re.findall() 这个方法来实现吧。

count = 0
for number in re.findall('\t(.+?)\n', b):
    ## add int(number.strip()) to count
0

你可以在循环之前创建一个空的列表,然后不是直接打印结果,而是把found这个值添加到这个列表里。这样的话,最后你可以把这个列表里的内容加起来(如果一切顺利,你应该得到一个包含“整数字符串”的列表)。

import re, os
path = "F:/s"
in_files = os.listdir(path)
l = []
for g in in_files:
  ...
  ...
  if m:
    found = m.group()
    l.append(found)

现在你的列表应该是这样的:['122', '74', '97'],所以你可以使用map()sum()来计算总和(在循环外进行):

print sum(map(int, l)) # 293

撰写回答