以前也有人问过和回答过类似的问题,但我想知道为什么我的代码不能产生正确的输出。
在我的txt文件中有几行代码如下:X-DSPAM-Confidence: 0.xxxx
0.xxxx值会有所不同。我需要从每个“X-DSPAM-置信度:”行中切出这一部分,并计算平均值。
可在此处下载txt文件:http://www.py4e.com/code3/mbox-short.txt
我的代码如下:
fname = input("Enter file name: ")
fh = open(fname)
count = 0
current = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue # Please do not change this line and develop the program based on it
count = count + 1 # I think this would count how many lines that starts with X-DSPAM-Confidence:
pos = line.find(':') # This should find me the position for ":"
number = line[pos+5:] # I think this should slice the number out
final = float(number) + current # Then I float the number and add to the current running number
print("Average spam confidence: ", final/count) # Finally, when the loop finishes with the file, print the average使用上面的代码,我得到了平均33.5925925926,但正确的答案应该是0.750718518519。
有没有人能开导一下我?
发布于 2020-07-17 01:24:25
按照您的要求,只需进行最少但必要的更改。
fname = input("Enter file name: ")
with open(fname, "r") as current_file:
# i can not stress enough the importance of the with method over
#open()/close()
content = current_file.readlines()
count = 0
current = 0
for line in content:
if not line.startswith("X-DSPAM-Confidence:"): continue
count = count + 1
pos = line.find(':')
number = line[pos+2:] # small error, it was not 5 but 2 instead
current = float(number) + current
print("Average spam confidence: ", current/count)https://stackoverflow.com/questions/62939878
复制相似问题