以下是我的代码:
import re
fname = raw_input ("Enter the file name: ")
try:
fh = open(fname)
except:
print "File name entered is not correct"
for line in fh:
line = line.rstrip()
x = re.findall('[0-9]+', line)
print x
number = map(int, x)
print sum(number)
我得到一个空列表,总和为零。不确定我在哪里弄错了。我正在使用Notepad ++
答案 0 :(得分:3)
你只使用最后一行中的数字,在你的情况下可能没有数字。你必须保留所有行的数字:
import re
fname = raw_input("Enter the file name: ")
numbers = []
with open(fname) as lines:
for line in lines:
numbers.extend(re.findall('[0-9]+', line))
print numbers
print sum(map(int, numbers))
答案 1 :(得分:1)
x
。它只保留最后一行,看起来是空的。
答案 2 :(得分:-1)
您每次迭代都会覆盖变量x
。可能的解决方案是
import re
fname = raw_input ("Enter the file name: ")
try:
fh = open(fname)
except:
print "File name entered is not correct"
exit()
sum = 0
for line in fh:
line = line.rstrip()
x = re.findall('[0-9]+', line)
sum += int(x[0])
print sum