繁体   English   中英

如何对一个文本文件中的所有数字求和?

[英]How to sum all the numbers in a text file?

我必须计算文件中任何数字的总和并打印总和。

数字定义为以0到9开头的数字,然后是0到9任意数目的字符串。

字母数字字符串(包括数字和字母的字符串)不包括在求和中。

这是文件的内容:

a b cddde ff 1
5
hH five lll 0
l 10
99 abcd7
9kk
0

因此,在这种情况下,答案将是115。

您需要做的只是使用item.isnumeric() 如果该项仅由数字而不是字母或其他字符组成,则它将返回true。

因此,您检查了wordList的所有项目,如果项目为isnumeric() ,则将其添加到total

infile = open(filename.txt, 'r')
content = infile.read()       
infile.close()

wordList = content.split()    
total = 0

for item in wordList:
    if item.isnumeric():
        total += int(item)

我建议使用RegEx:

import re

with open('file') as f:
    print(sum(int(i) for i in re.findall(r'\b\d+\b', f.read())))

在这种情况下:

  • \\b+匹配所有数字,并且\\b检查数字之后(或之前)是否存在字母,以便我们可以忽略abcd79kk

  • re.findall()尝试使用RegEx \\b\\d+\\b查找文件中的所有数字并返回一个列表。

  • int(i) for i in re.findall(r'\\b\\d+\\b') 列表压缩 int(i) for i in re.findall(r'\\b\\d+\\b')re.findall()返回的列表中的所有元素转换为int对象。

  • sum()内置函数对列表的元素求和,然后返回结果。

在线RegEx演示

def function():

    infile = open("test.txt", 'r')
    content = infile.read()       
    infile.close()
    wordList = content.split()

    total = 0

    for i in wordList:
        if i.isnumeric():
            total += int(i)
    return total

在此解决方案中,我将文件命名为test.txt。 想法是您遍历wordList,这是一个包含test.txt中拼接的每个项目的列表(尝试在循环之前打印wordList以便自己查看)。 然后,我们尝试将每个项目都转换为int格式(假定文件中没有小数,如果可以,则可以包含float转换)。 然后,我们捕获ValueError,该错误在将“ a”转换为int时引发。

暂无
暂无

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

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