尝试从.txt文档中提取数字,并在python2.7中使用正则表达式求和
下面是我的代码:尝试从.txt文档中提取数字,并在python2.7中使用正则表达式求和,python,regex,python-2.7,Python,Regex,Python 2.7,下面是我的代码: 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)
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)
我得到一个空列表,总和为零。不知道我在哪里犯了错误。我正在使用记事本++
x
在循环的每个迭代中都会被替换。它只保留最后一行,看起来是空的。x
在循环的每次迭代中都会被替换。它只保留最后一行,看起来是空的。您只使用最后一行中的数字,在您的案例中可能没有数字。您必须保留所有行的编号:
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))
您只使用最后一行中的数字,在您的案例中可能没有数字。您必须保留所有行的编号:
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))
每次迭代都会覆盖变量
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
每次迭代都会覆盖变量
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
嗨,丹尼尔,谢谢你的修改版本。你的代码工作得很好!。然而,你能解释一下我的代码到底哪里出错了吗?我知道这只是把数字放在最后一行,但我该如何避免呢?有什么方法可以做到这一点,而不必在开始时创建一个空列表,然后扩展它?@studentoflife:您也可以一次生成总和。对我来说,似乎你想在总结之前看到所有的数字。嗨,丹尼尔,谢谢你修改的版本。你的代码工作得很好!。然而,你能解释一下我的代码到底哪里出错了吗?我知道这只是把数字放在最后一行,但我该如何避免呢?有什么方法可以做到这一点,而不必在开始时创建一个空列表,然后扩展它?@studentoflife:您也可以一次生成总和。对我来说,似乎你想在求和之前查看所有数字。我应该如何避免?我应该如何避免?
int
不是为列表定义的。int
不是为列表定义的。