2016-11-15 87 views
-1

我讀這本格式有數據的文本文件:分裂 - ValueError異常:需要比1點的值更解壓

column : row 

這是一些示例數據:

Name of the Property : North Kensington Upcycling Store and Cafe 
Availability : Now 
Interest Level : 74 people are looking right now 
Area : 1,200 sqft 
Retail Type : No 
Bar & Restaurant Type : No 

我的代碼給這個錯誤:

ValueError: need more than 1 value to unpack 

在這一行:

k,v = txt_line.split(":") 

我的代碼:

import pandas 
txt_file = r"patty.txt" 
txt = open(txt_file, "r") 
txt_string = txt.read() 
txt_lines = txt_string.split("\n") 
txt_dict = {} 

for txt_line in txt_lines: 
    print(txt_line) 
    k,v = txt_line.split(":") 
    k = k.strip() 
    v = v.strip() 
    if k in txt_dict: 
     list = txt_dict.get(k) 
    else: 
     list = [] 
    list.append(v) 
    txt_dict[k]=list 
print (pandas.DataFrame.from_dict(txt_dict, orient="index")) 
+0

我試圖用最少的數據運行它只說前3行,我仍然得到錯誤..我在這裏做邏輯錯誤? – roy

回答

1

如果輸入文件的行是空的或丟失冒號,split回報只有1元,你會得到錯誤。

要發揮它的安全,我會做一個尺寸檢查,以避免該異常,並打印在解析時一個明確的信息是不可能的(我加空條跳躍,以避免在這種情況下崩潰)

if txt_line.strip(): 
    # line is not empty or just blanks 
    toks = txt_line.split(":") 
    if len(toks)==2: 
     # unpack safely 
     k,v = toks 
    else: 
     print("unable to parse {}".format(txt_line)) 
+0

法布爾,當我試圖在這裏複製和粘貼數據時,實際上沒有出現錯誤。我不認爲這是問題。 – roy

+0

你可以改變你的代碼,看看會發生什麼嗎?必須是文件末尾的空行。 –

+0

你需要一分鐘! – roy

相關問題