此问题的基本概述是读取文件,使用re.findall()查找整数,查找“ [0-9] +”的正则表达式,然后将提取的字符串转换为整数并将其求和。
我已经解决了问题,但我想进一步说明一下,将代码压缩为两行。
这是我的原始代码:
import re
fh = raw_input("Enter filename: ")
#returns regex_sum_241882.txt as default when nothing is entered
if len(fh)<1 : fh = "regex_sum_241882.txt"
file = open(fh)
sums = list()
#goes through each line in the file
for line in file:
#finds the numbers in each line and puts them in a list
nums = re.findall('[0-9]+',line)
#adds the numbers to an existing list
for num in nums:
sums.append(int(num))
#sums the list
print sum(sums)
现在,这是我当前的紧凑代码:
import re
lst = list()
print sum(for num in re.findall('[0-9]+',open("regex_sum_241882.txt").read())): int(num))
它不起作用,并给我SyntaxError:无效的语法
谁能指出我正确的方向?
我觉得我在做同样的事情,但不确定语法错误是什么。
最佳答案
尝试这种方式:
print sum(int(num) for num in re.findall('[0-9]+', open("regex_sum_241882.txt").read()))