[英]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)
我有一個代碼依賴於我閱讀文本文件,在有數字的地方打印數字,在有字符串而不是數字的地方打印特定的錯誤消息,然后將所有數字相加並打印它們的總和(然后只保存數字到一個新的文本文件)。
因此,您必須執行以下操作:
這是一種方法:
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.