如何对一个文本文件中的所有数字求和? [英] How to sum all the numbers in a text file?
问题描述
我必须计算文件中任何数字的总和并打印总和.
I have to calculate the sum of any numbers in the file and print the sum.
数字定义为以0到9开头的数字,然后是0到9任意数目的字符串.
A number is defined as any string beginning with a digit 0 through 9 followed by any number of digits 0 through 9.
字母数字字符串(包括数字和字母的字符串)不包括在求和中.
Alphanumeric strings (strings including both numbers and letters) are not to be included in the summation.
这是文件的内容:
a b cddde ff 1
5
hH five lll 0
l 10
99 abcd7
9kk
0
在这种情况下,答案是115.
So the answer would be 115 in this case.
推荐答案
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时引发.
In this solution, I named the file test.txt. The idea is you loop through wordList which is a list containing every item spliced in test.txt (try printing wordList before the loop to see for yourself). We then try to cast each item as a int (this assumes no decimals will be in the file, if so you can include a float cast). We then catch ValueError which gets raised when casting i.e 'a' as an int.
这篇关于如何对一个文本文件中的所有数字求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!