[英]How to find and extract values from a txt file?
編寫一個程序,提示輸入文件名,然后打開該文件並通讀該文件,查找以下形式的行:
X-DSPAM-Confidence: 0.8475
對這些行進行計數,從每行中提取浮點值,計算這些值的平均值並生成如下所示的 output。 不要在您的解決方案中使用sum()
function 或名為sum
的變量。*
這是我的代碼:
fname = input("Enter a file name:",)
fh = open(fname)
count = 0
# this variable is to add together all the 0.8745's in every line
num = 0
for ln in fh:
ln = ln.rstrip()
count += 1
if not ln.startswith("X-DSPAM-Confidence: ") : continue
for num in fh:
if ln.find(float(0.8475)) == -1:
num += float(0.8475)
if not ln.find(float(0.8475)) : break
# problem: values aren't adding together and gq variable ends up being zero
gq = int(num)
jp = int(count)
avr = (gq)/(jp)
print ("Average spam confidence:",float(avr))
問題是當我運行代碼時它說有一個錯誤,因為num
的值為零。 所以我然后收到這個:
ZeroDivisionError: division by zero
當我將num
的初始值更改為None
時,會出現類似的問題:
int() argument must be a string or a number, not 'NoneType'
當我把它放在代碼的頂部時,python COURSERA autograder 也不接受它:
from __future__ import division
他們給我們的示例數據的文件名為“mbox-short.txt”。 這是一個鏈接http://www.py4e.com/code3/mbox-short.txt
我像下面一樣編輯了你的代碼。 我認為您的任務是找到X-DSPAM-Confidence:旁邊的數字。 我使用您的代碼來識別X-DSPAM-Confidence:行。 然后我用':'分割字符串然后我取了第一個索引並轉換為浮點數。
fname = input("Enter a file name:",)
fh = open(fname)
count = 0
# this variable is to add together all the 0.8745's in every line
num = 0
for ln in fh:
ln = ln.rstrip()
if not ln.startswith("X-DSPAM-Confidence:") : continue
count+=1
num += float(ln.split(":")[1])
gq = num
jp = count
avr = (gq)/(jp)
print ("Average spam confidence:",float(avr))
with
打開文件,因此文件會自動關閉。X-DSPAM-Confidence: 0.6961
的形式,因此請在空格處拆分它們。
'X-DSPAM-Confidence: 0.6961'.split(' ')
創建一個列表,其中數字位於列表索引 1 處。fname = input("Enter a file name:",)
with open(fname) as fh:
count = 0
num = 0 # collect and add each found value
for ln in fh:
ln = ln.rstrip()
if not ln.startswith("X-DSPAM-Confidence:"): # find this string or continue to next ln
continue
num += float(ln.split(' ')[1]) # split on the space and add the float
count += 1 # increment count for each matching line
avr = num / count # compute average
print(f"Average spam confidence: {avr}") # print value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.