2014-12-13 131 views
0

我正在學習python,我喜歡在少量代碼中完成多少操作,但是我對語法感到困惑。我只是試圖遍歷字典並打印出每個項目和值。在python字典中迭代和打印單詞

這裏是我的代碼:

words = {} 
value = 1 

for line in open("test.txt", 'r'): 
    for word in line.split(): 
     print (word) 
     try: 
      words[word] += 1 
     except KeyError: 
      #wur you at key? 
      print("no") 
      words[word]=1 

for item in words: 
    print ("{",item, ": ", words[item][0], " }") 

我當前的打印語句不工作,我無法找到使用多變量大print語句的一個很好的例子。我將如何正確打印?

+0

你說的意思是什麼「不工作」?如果你向我們提供了一個[MCVE](http://stackoverflow.com/help/mcve),或者用'test.txt'的內容,或者更好的是用源代碼中定義的'words',這將會有所幫助。然後你可以顯示預期的和實際的輸出。 – abarnert 2014-12-13 03:51:54

回答

1

您的問題似乎是,你要打印words[item][0],但words[item]總是將成爲一個號碼,並且號碼不能被索引。

所以,只是......不要做:

print ("{",item, ": ", words[item], " }") 

這足以解決它,但有辦法,你可以改善這個代碼:

  • print有多個參數在每個空間之間放置一個空間,所以當你可能不想要所有這些空間時,你將最終打印{ item : 3 }。您可以通過使用關鍵字參數sep=''來解決該問題,但更好的解決方案是使用字符串格式或%運算符。
  • 您可以通過遍歷words.items()而不是words來同時獲取密鑰和值。
  • 通過使用setdefault方法或使用defaultdict或更簡單地說,您可以使用Counter來簡化整個「存儲默認值(如果其中一個不存在的話)」。
  • 您應該始終關閉打開的文件 - 最好使用with語句。
  • 要保持風格一致 - 不要在一些功能之後放置空格,但不要放置其他空間。

所以:

import collections 
with open("test.txt") as f: 
    words = collections.Counter(word for line in f for word in line.split()) 
for item, count in words.items(): 
    print("{%s: %d}" % (item, count)) 
+0

謝謝!我試圖解決一些基本的python問題來處理它,並且我還有很多東西需要學習。 – 2014-12-13 04:10:18

-1

通過,你在這裏做一個字典迭代,最好的辦法是通過循環鍵和值,通過循環每次開箱鍵值元組:

for item, count in words.items(): 
    print("{", item, ": ", count, "}") 

而作爲一個側面說明,在構建數組的那個循環中,您並不需要那種異常處理邏輯。如果該鍵不在字典詞典get()方法可以返回一個默認值,簡化您的代碼如下:

words[word] = words.get(word, 0) + 1 
+0

我收到以下錯誤:'ValueError:太多的值解壓縮(預期2)' – 2014-12-13 03:55:17

+0

這是錯誤的。當你迭代一個'dict'時,你只需要得到它的鍵,而不是它的鍵 - 值對。如果你想要後者,你必須使用'items'方法(正如我的答案中所解釋的)。另外,這並不能解釋他的代碼有什麼問題;如果您將他的代碼翻譯爲使用'items',則它將是'item',word.items():',然後是'print'調用中的word [0]',並且您會得到完全相同的他開始的錯誤。 – abarnert 2014-12-13 04:00:32

+0

固定使用'items()'。我認爲我不必特別解釋爲什麼OP的代碼是錯誤的,因爲你這樣做。在我看來,我在這個答案中出現的代碼是最好的方式;這是因爲它更習慣地閱讀。當我最初發布答案時,它已經放棄了我需要'items()'的想法。 – APerson 2014-12-13 04:03:48

0

可以使用dict.get並能消除嘗試,除塊。

words = {} 

for line in open("test.txt", 'r'): 
    for word in line.split(): 
     print (word) 
     words[word] = words.get(word,0) +1 

for word,count in words.items(): 
    print(word,count) 

dict.get它返回鍵,存在於詞典否則默認值,如果
語法:dict.get(key[,default])

你也可以覆蓋__missing__

class my_dict(dict): 
    def __missing__(self,key): 
     return 0 


words = my_dict() 

for line in open("test.txt", 'r'): 
    for word in line.split(): 
     print (word) 
     words[word] += 1 

for word,count in words.items(): 
    print(word,count)