如何在 Python 中对文本文件中的数字求和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28924474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sum numbers from a text file in Python
提问by Megan
I have a code that relies on me reading a text file, printing off the numbers where there are numbers, printing off specific error messages where there are strings instead of numbers, then summing ALL the numbers up and printing their sum (then saving ONLY the numbers to a new text file).
我有一个代码依赖于我阅读文本文件,在有数字的地方打印数字,在有字符串而不是数字的地方打印特定的错误消息,然后将所有数字相加并打印它们的总和(然后只保存数字到一个新的文本文件)。
I have been attempting this problem for hours, and I have what is written below.
我已经尝试这个问题几个小时了,我有下面写的内容。
I do not know why my code does not seem to be summing up properly.
我不知道为什么我的代码似乎没有正确总结。
And the python code:
和python代码:
f=open("C:\Users\Emily\Documents\not_just_numbers.txt", "r")
s=f.readlines()
p=str(s)
for line in s:
printnum=0
try:
printnum+=float(line)
print("Adding:", printnum)
except ValueError:
print("Invalid Literal for Int() With Base 10:", ValueError)
for line in s:
if p.isdigit():
total=0
for number in s:
total+=int(number)
print("The sum is:", total)
采纳答案by Burhan Khalid
I have a code that relies on me reading a text file, printing off the numbers where there are numbers, printing off specific error messages where there are strings instead of numbers, then summing ALL the numbers up and printing their sum (then saving ONLY the numbers to a new text file).
我有一个代码依赖于我阅读文本文件,在有数字的地方打印数字,在有字符串而不是数字的地方打印特定的错误消息,然后将所有数字相加并打印它们的总和(然后只保存数字到一个新的文本文件)。
So you have to do the following:
因此,您必须执行以下操作:
- Print numbers
- Print a message when there isn't a number
- Sum the numbers and print the sum
- Save only the numbers to a new file
- 打印数字
- 没有号码时打印消息
- 对数字求和并打印总和
- 仅将数字保存到新文件
Here is one approach:
这是一种方法:
total = 0
with open('input.txt', 'r') as inp, open('output.txt', 'w') as outp:
for line in inp:
try:
num = float(line)
total += num
outp.write(line)
except ValueError:
print('{} is not a number!'.format(line))
print('Total of all numbers: {}'.format(total))
回答by David Ruiz
Every time you enter a new line you reset the total to zero if the number is a digit.
每次输入新行时,如果数字是数字,则将总数重置为零。
You might want your total to initialize before you enter the loop.
您可能希望在进入循环之前初始化您的总数。
I tried debugging the for loop using the isdigit and isalpha apparently every new line is not considered a digit or alphanumeric these always evaluate to false
我尝试使用 isdigit 和 isalpha 调试 for 循环,显然每个新行不被视为数字或字母数字,这些总是评估为 false
As it turns out you don't need the for loop you've done most of the program with your try except statement
事实证明,您不需要 for 循环,您已经使用 try except 语句完成了大部分程序
Here's how I did it on my system.
这是我在我的系统上的做法。
f = open("/home/david/Desktop/not_just_numbers.txt", 'r')
s = f.readlines()
p = str(s)
total = 0
for line in s:
#print(int(line))
printnum = 0
try:
printnum += float(line)
total += printnum
#print("Adding: ", printnum)
except ValueError:
print("Invalid Literal for Int() With Base 10:", ValueError)
print("The sum is: ", total)
回答by 7stud
Here is what you can do:
您可以执行以下操作:
data.txt:
数据.txt:
1
2
hello
3
world
4
code:
代码:
total = 0
with open('data.txt') as infile:
with open('results.txt', 'w') as outfile:
for line in infile:
try:
num = int(line)
total += num
print(num, file=outfile)
except ValueError:
print(
"'{}' is not a number".format(line.rstrip())
)
print(total)
--output:--
'hello' is not a number
'world' is not a number
10
$ cat results.txt
1
2
3
4
回答by lvc
You are checking the wrong condition:
您正在检查错误的条件:
for line in s:
if p.isdigit():
p
is this:
p
这是:
s=f.readlines()
p=str(s)
Being a str
ified version of a list, it will start with a '['
, and hence p.isdigit()
will always be false. You instead want to check line.isdigit()
, and you want to only initialise total
once instead of each time around the loop:
作为str
列表的明确版本,它将以 a 开头'['
,因此p.isdigit()
将始终为 false。相反line.isdigit()
,您想要检查,并且您只想初始化total
一次而不是每次都在循环中:
total = 0
for line in f:
if line.isdigit():
total += int(line)
Note that by iterating over f
directly, you also don't need to ever call readlines()
.
请注意,通过f
直接迭代,您也不需要调用readlines()
.
回答by Sakib Ahammed
you can also try this:
你也可以试试这个:
f=open("C:\Users\Emily\Documents\not_just_numbers.txt", "r")
ww=open("C:\Users\Emily\Documents\not_just_numbers_out.txt", "w")
s=f.readlines()
p=str(s)
for line in s:
#printnum=0
try:
#printnum+=float(line)
print("Adding:", float(line))
ww.write(line)
except ValueError:
print("Invalid Literal for Int() With Base 10:", ValueError)
total=0
for line in s:
if line.strip().isdigit():
total += int(line)
print("The sum is:", total)
here str.strip([chars])
means
这里的str.strip([chars])
意思是
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped
返回删除前导和尾随字符的字符串副本。chars 参数是一个字符串,指定要删除的字符集。如果省略或 None,则 chars 参数默认为删除空格。chars 参数不是前缀或后缀;相反,其值的所有组合都被剥离
回答by Diego Roberto Dos Santos
$ echo -e '1/n2/n3/n4/n5' | python -c "import sys; print sum(int(l) for l in sys.stdin)"