如何对 Python 中的文本文件中的数字求和

How to sum numbers from a text file in Python

我有一个代码依赖于我读取一个文本文件,在有数字的地方打印出数字,在有字符串而不是数字的地方打印出特定的错误消息,然后将所有数字相加并打印它们的总和(然后仅将数字保存到新的文本文件中)。

我已经尝试这个问题好几个小时了,我有下面写的内容。

我不知道为什么我的代码似乎没有正确总结。

和 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)

每次输入新行时,如果数字是数字,则将总数重置为零。

您可能希望在进入循环之前初始化总计。


我尝试使用 isdigit 和 isalpha 调试 for 循环 显然,每一行都不被视为数字或字母数字,这些总是评估为 false

事实证明你不需要 for 循环你已经用你的 try except 语句完成了大部分程序

这是我在我的系统上的做法。

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)

您可以执行以下操作:

data.txt:

1
2
hello
3
world
4

代码:

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

您正在检查错误的条件:

for line in s: 
    if p.isdigit():

p是这样的:

s=f.readlines()
p=str(s)

作为列表的 str 化版本,它将以 '[' 开头,因此 p.isdigit() 始终为假。相反,您想要检查 line.isdigit(),并且只想初始化 total 一次,而不是每次循环:

total = 0
for line in f:
    if line.isdigit():
        total += int(line)

请注意,通过直接遍历 f,您也不需要调用 readlines()

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).

因此您必须执行以下操作:

  1. 打印数字
  2. 没有号码时打印消息
  3. 对数字求和并打印总和
  4. 仅将数字保存到新文件

这是一种方法:

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))

你也可以试试这个:

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)

这里str.strip([chars])表示

Return 删除了前导和尾随字符的字符串副本。 chars 参数是一个字符串,指定要删除的字符集。如果省略或 None,chars 参数默认为删除空格。 chars 参数不是前缀或后缀;相反,其值的所有组合都被剥离

$ echo -e '1/n2/n3/n4/n5' | python -c "import sys; print sum(int(l) for l in sys.stdin)"

这是对文件中所有数字求和的非常简短的方法(您必须添加 try 和 except)

import re
print(sum(float(num) for num in re.findall('[0-9]+', open("C:\Users\Emily\Documents\not_just_numbers.txt", 'r').read())))