繁体   English   中英

如何对 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)

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

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

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

这是对文件中所有数字求和的一种非常简短的方法(您必须添加 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())))

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

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


我尝试使用 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)

您可以执行以下操作:

数据.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()

你也可以试试这个:

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])表示

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

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

从包含由新行分隔的数字的文件中读取:

    total = 0
    with open("file_with_numbers.txt", "r") as f:
        for line in f:
            total += int(line)
    print(total)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM