2011-03-10 288 views
7

我的程序在嘗試將字符串從字符串列表轉換爲浮點數時給我一個錯誤。該列表是從CSV文本文件中的行中讀取的,然後分成一個列表。我如何做這項工作,爲什麼會出錯?下面是代碼的相關位:爲什麼float()無法將我的字符串轉換爲float?

def Main(): 
    srcf = open(bkp, 'r') 
    for line in srcf: 
     liLn = line.split(',') 

...那麼下面的函數被調用......

def Pred_PSME(liLn): 
    dbh = float(liLn[6]) 

下面是該文件的行:

1345327,20486,"ABCO","Abies concolor","Y","Y","31.496","0.0779","19.3567",,"0.5602","0",1,"0.9268","11.8968","2.6832","6.6646","2399.256",54.47,24.15,248.47,42.19,9.16,8.16,9.23,272.27,264.11,369.30,345.15,71.80,0.00,0.00,4393.57,4106.22,3239.25,3142.07,854.30,0.00,0.00,,12.70,10.16,15.24,0.02,0.04,0.38,0.38,0.00,0.00,1.95,1.83,1.44,1.40

我收到此錯誤消息:

Traceback (most recent call last): 
    File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 263, in <module> 
    Main() 
    File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 36, in Main 
    li_tBQI = BQI_Calc(liLn) 
    File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 63, in BQI_Calc 
    di_eqns = {"PSME": Pred_PSME(liLn), "ABAM":Pred_ABAM(liLn), \ 
    File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 172, in Pred_PSME 
    dbh = float(liLn[6]) 
ValueError: could not convert string to float: "31.496" 

我在Ubuntu Linux計算機上使用Python 2.7。

+1

看起來像'liLn [6]'包含''31.496「',包括引號,也許你應該在將它們傳遞給'float()'之前去掉它們?這只是一個猜測。另外,讓我成爲第一個說,歡迎來到SO! :) – 2011-03-10 03:13:46

+5

你爲什麼不使用'csv'? – 2011-03-10 03:18:38

+0

無論您是否使用'csv'模塊,您都應該考慮將所有這些值放入一個容器類(例如'collections'模塊中的'namedtuple' tuple子類),以使它們更容易和更易讀取,就像例如,「liLn.dbh」。如果沒有別的辦法,你可以定義包含它們命名的字段索引的整型變量。例如,設置'DBH = 2'可讓您編寫'liLn [DBH]'而不是'liLn [6]'。 – martineau 2011-03-21 08:22:47

回答

9

您需要去掉字符串中的雙引號。然後你會給出一個float()可以轉換的合法浮點字符串。

+5

哈哈!謝謝,這讓它工作。我要戴上我的帽子,在角落裏坐一會兒。 – cfwschmidt 2011-03-10 03:57:02

相關問題