【发布时间】:2020-07-16 17:03:06
【问题描述】:
之前有人提出并回答了类似的问题,但我想知道为什么我的代码没有产生正确的输出。
我的 txt 文件中有几行如下所示:X-DSPAM-Confidence: 0.xxxx
0.xxxx 值会有所不同。我需要从每个“X-DSPAM-Confidence:”行中切出该部分并计算平均值。
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。
谁能赐教?
【问题讨论】:
-
你永远不要重复使用
final,最后做current= float(number) + current和current/count
标签: python string parsing split