这个问题的基本大纲是读取文件,使用 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))
它不起作用并给我语法错误:无效语法
谁能指出我正确的方向?我觉得我在做同样的事情,但我不确定语法错误是关于什么的。
试试这个方式:
print sum(int(num) for num in re.findall('[0-9]+', open("regex_sum_241882.txt").read()))