2017-10-07 30 views
1

好吧,所以我是新來的python,我目前正在採取python爲每個人當然(py4e)。Python ValueError:float:參數:。是不是12號線

我們的教訓7.2的任務是做到以下幾點:

7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:

X-DSPAM-Confidence: 0.8475 

Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution. You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.

我無法弄清楚。 https://gyazo.com/a61768894299970692155c819509db54 第12行是num = float(balue) + float(num)保持演戲了:當我運行這段代碼(見截圖),我不斷收到此錯誤

ValueError: float: Argument: . is not number on line 12 

。當我刪除從balue浮動然後我再弄它說

"TypeError: cannot concatenate 'str' and 'float' objects on line 12".

燦參數轉換成浮動或者是它只是一個字符串?這可能是問題,但我不知道它是否屬實,即使是這樣,我不知道如何修復我的代碼。

+3

不,謝謝。這不是一個網站,可以爲您完成作業。如果您的代碼存在特定問題,請參閱如何創建[mcve]。 –

+1

你會刪除代碼的屏幕截圖,並用問號中的代碼替換爲文本格式?代碼作爲圖像與剪貼板,搜索引擎和屏幕閱讀器不兼容,因此不是用於提供工作的理想格式。這個問題可能會被擱置在這個基礎上,但如果你能修復它,我們可以阻止它關閉(或者如果它關閉,我們可以在它關閉後重新打開它)。 – halfer

回答

1

你的方法並不那麼糟糕,我會說。但是,我沒有得到你想要的for balue in linez,因爲這是迭代linez中包含的字符。你寧可想要浮起(linez)。我想出了一個緊密的解決方案看起來像這樣:

fname = raw_input("Enter file name: ") 
print(fname) 

count = 0 
num = 0 
with open(fname, "r") as ins: 
    for line in ins: 
     line = line.rstrip() 
     if line.startswith("X-DSPAM-Confidence:"): 
      num += float(line[20:]) 
      count += 1 

print(num/count) 

這只是爲了讓你在正確的軌道上,我還沒有驗證答案或腳本的正確性,因爲這應該包含你的功課。

相關問題