Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何对文本文件中的所有数字求和?_Python_File - Fatal编程技术网

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

Python 如何对文本文件中的所有数字求和?,python,file,Python,File,我必须计算文件中所有数字的总和,然后打印总和 数字定义为以数字0到9开头的任意字符串,后跟任意数量的数字0到9 字母数字字符串(包括数字和字母的字符串)不包括在总和中 这是文件的内容: a b cddde ff 1 5 hH five lll 0 l 10 99 abcd7 9kk 0 在这种情况下,答案是115 def function(): infile = open("test.txt", 'r') content = infile.read()

我必须计算文件中所有数字的总和,然后打印总和

数字定义为以数字0到9开头的任意字符串,后跟任意数量的数字0到9

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

这是文件的内容:

a b cddde ff 1
5
hH five lll 0
l 10
99 abcd7
9kk
0
在这种情况下,答案是115

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进行循环,wordList是一个包含test.txt中拼接的每个项目的列表(请尝试在循环之前打印wordList,以便自己查看)。然后,我们尝试将每个项转换为int(这假设文件中没有小数,如果可以包含浮点转换的话)。然后,我们捕获将“a”转换为int时引发的ValueError。

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

因此,您需要检查
单词列表中的所有项目,如果项目
是numeric()
则将该项目添加到
总计中

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)

我建议使用正则表达式:

import re

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

  • \b+
    匹配所有数字,
    \b
    检查数字后面(或之前)是否有字母,以便我们可以忽略
    abcd7
    9kk

  • 尝试使用RegEx
    \b\d+\b
    查找文件中的所有数字并返回列表

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

  • 内置函数对列表中的元素求和,并返回结果


这里有问题吗?我应该找到粗体斜体列出的内容的总和,但我不知道如何总是用所使用的语言标记问题,并包括错误​​​​​​​​​​​​​​​@MarkyPython:请不要在标题前添加
Python:
,因为这个问题是有标签的,所以不需要,应该删除。为什么要在Python内置了
isnumeric()
函数的情况下大费周章呢?