2013-07-01 57 views
9

我想填充我的文本文件的內容的字典嗎?(‘out3.txt’)如何解決ValueError異常:太多值解壓」在Python

我的文本文件,是的。形式:

vs,14100 

mln,11491 

the,7973 

cts,7757 

...等等...

我想我的字典answer是形式:

answer[vs]=14100 

answer[mln]=11491 

...等等...

我的代碼是:

import os 
import collections 
import re 
from collections import defaultdict 

answer = {} 
answer=collections.defaultdict(list) 
with open('out3.txt', 'r+') as istream: 
    for line in istream.readlines(): 
     k,v = line.strip().split(',') 
     answer[k.strip()].append(v.strip()) 

但是,我得到:

ValueError: too many values to unpack

我該如何解決這個問題?

+4

我懷疑輸入文件中的其中一行有多個逗號。試試'grep',。*,'out3.txt'。 –

回答

10

你在你的輸入文件具有空line S和我懷疑你有沒有跟我們分享了line S的一箇中有太多的逗號(,因此「太多的值來解壓縮「)。

您可以防止這一點,就像這樣:

import collections 

answer = collections.defaultdict(list) 
with open('out3.txt', 'r+') as istream: 
    for line in istream: 
     line = line.strip() 
     try: 
      k, v = line.split(',', 1) 
      answer[k.strip()].append(v.strip()) 
     except ValueError: 
      print('Ignoring: malformed line: "{}"'.format(line)) 

print(answer) 

注:通過傳遞1str.split(),一切後,第一個逗號將被分配到v;如果這不是所期望的行爲,並且您希望這些行被拒絕,則可以刪除此參數。

+0

還是一樣的錯誤! –

+0

啊是的。我已經更新了我的答案。 – Johnsyweb

+0

謝謝!它的工作! –

2

您的文本文件有空行,無法拆分。您需要檢測,如果該行是空:

for line in istream: 
    line = line.strip() 
    if line: 
     k,v = line.split(',') 
     answer[k.strip()].append(v.strip()) 
+1

我仍然得到相同的錯誤! –

3

您的解決方案不會提供您所需的輸出。你必須(假設它的工作),answer['vs'] = [14100],下面做你的原意:

import csv 

with open('out3.txt') as f: 
    reader = csv.reader(f, delimiter=',') 
    answer = {line[0].strip():line[1].strip() for line in reader if line} 
+1

使用'csv'的+1(除非輸入文件非常具體,簡單)。 – pepr

1

你不需要collections這裏。普通的舊字典就夠了:

answer = {} 
with open('out3.txt', 'r+') as f: 
    for line in f: 
     lst = line.split(',') 
     if len(lst) == 2: 
      k = lst[0].strip() 
      v = lst[1].strip() 
      answer[k] = v 

print(answer['mln']) 
print(answer.get('xxx', 'not available')) 

通知的answer.get()類似於answer[],但你可以提供defaul值。

您不應該在循環中使用.readlines()。即使是空行也包含換行符。這樣測試if line:不檢測空行。或者,您必須首先去除(或rstrip),或者您可以將該線分割到列表中並測試元素的數量。

0

當我將django版本1.5更改爲1.3時,出現同樣的錯誤。用戶對象在不同版本中具有不同的值。也許這是一樣的情況。我在我使用的函數中再次設置了值,並且它可以工作。

相關問題