我对python相对较新,并且卡在了下面: 以下是我正在使用的代码
import re
handle = open ('RegExWeek2.txt')
for line in handle:
line = line.rstrip()
x = re.findall('[0-9]+', line)
if len(x) > 0:
print x
此代码的返回如下所示:
['7430']
['9401', '9431']
['2248', '2047']
['5517']
['3184', '1241']
['9939']
['2185', '9450', '8428']
['369']
['3683', '6442', '7654']
问题:如何将其与一个列表合并并总结数字? 请帮忙
答案 0 :(得分:0)
您可以像这样更改代码,
handle = open ('RegExWeek2.txt')
num = []
for line in handle:
num.extend(re.findall('[0-9]+', line))
print sum(int(i) for i in num)
由于您正在使用re.findall
,因此不需要此line.rstrip()
行。
而且,由于我们在+
旁边使用[0-9]
(重复前一个令牌一次或多次,因此x不可能成为空列表)不是*
(零次或多次)
答案 1 :(得分:0)
不需要rstrip
,您应该使用with
打开文件:
import re
all_numbers = []
with open('RegExWeek2.txt') as file:
for line in file:
numbers = re.findall('[0-9]+', line)
for number in numbers:
all_numbers.append(int(number))
print(sum(all_numbers))
这是真正的初学者代码,也是您的直接翻译。以下是我的写作方式:
with open('RegExWeek2.txt') as file:
all_numbers = [int(num) for num in re.findall('[0-9]+', file.read())]
print(sum(all_numbers))