問題描述
我有一個代碼依賴于我讀取文本文件,打印出有數字的數字,打印出有字符串而不是數字的特定錯誤消息,然后將所有數字相加并打印它們的總和(然后僅將數字保存到新的文本文件中).
I have a code that relies on me reading a text file, printing off the numbers where there are numbers, printing off specific error messages where there are strings instead of numbers, then summing ALL the numbers up and printing their sum (then saving ONLY the numbers to a new text file).
我已經嘗試這個問題幾個小時了,我有下面寫的內容.
I have been attempting this problem for hours, and I have what is written below.
我不知道為什么我的代碼似乎沒有正確總結.
I do not know why my code does not seem to be summing up properly.
還有python代碼:
And the python code:
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)
推薦答案
我有一個代碼,它依賴于我讀取文本文件,打印出有數字的數字,打印出特定的錯誤消息其中有字符串而不是數字,然后將所有數字起來并打印它們的總和(然后只將數字保存到新的文本文件).
I have a code that relies on me reading a text file, printing off the numbers where there are numbers, printing off specific error messages where there are strings instead of numbers, then summing ALL the numbers up and printing their sum (then saving ONLY the numbers to a new text file).
所以你必須做到以下幾點:
So you have to do the following:
- 打印數字
- 當沒有數字時打印一條消息
- 將數字相加并打印出總和
- 僅將數字保存到新文件中
這是一種方法:
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))
這篇關于如何在 Python 中對文本文件中的數字求和的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!