2011-06-15 71 views
1

因此,我有一個單詞列表`wordList = list()'。現在,我使用此代碼Python-計算單詞列表中的每個字母

cnt = Counter() 
for words in wordList: 
     for letters in words: 
      cnt[letters]+=1 

不過,我想它來計算不同的計數每個單詞的每個字母在整個列表。我希望函數能夠從列表中的所有單詞中找到最常見的單詞,但只需對每個單詞的每個字母進行一次計數(忽略某些單詞可能具有同一字母的多個副本的事實)。

例如,如果列表中包含'happy,harpy and hasty',那麼開心的兩個p應該只計算一次。所以函數應該返回一個最高頻率的字母列表(按順序),而不用重複計算。在上述情況下,將「H,A,P,Y,R,S」

+1

在你的例子中,y用3個單詞,但p只用2,所以結果應該在p之前有y。 – 2011-06-15 05:01:26

回答

5
cnt = Counter() 
for words in wordList: 
     for letters in set(words): 
      cnt[letters]+=1 
6

添加set電話:

cnt = Counter() 
for word in wordList: 
     for letter in set(word): 
      cnt[letter]+=1 
2
cnt = Counter() 
for word in wordList: 
    lSet = set(word) 
    for letter in lSet: 
     cnt[letter] +=1    
+0

這是寫的不正確。 – 2011-06-15 05:23:21

+0

謝謝,我修正了錯字 – 2011-06-15 05:32:09

2

可以消除forupdate,哪些更新從可迭代計數(在這種情況下,字符串):

from collections import Counter 
words = 'happy harpy hasty'.split() 
c=Counter() 
for word in words: 
    c.update(set(word)) 
print c.most_common() 
print [a[0] for a in c.most_common()] 

[('a', 3), ('h', 3), ('y', 3), ('p', 2), ('s', 1), ('r', 1), ('t', 1)] 
['a', 'h', 'y', 'p', 's', 'r', 't'] 
3

使用迭代組合子在itertools的另一種方法:

import collections 
import itertools 

cnt = collections.Counter(itertools.chain.from_iterable(itertools.imap(set, wordList))) 
+0

你應該真的使用chain.from_iterable,否則* arg擴展將強制imap一次全部被評估 – 2011-06-15 05:48:29

+0

@gnibbler感謝提醒---舊習慣難改! – 2011-06-15 06:30:42

1

這產生從每個字的一組並將它們傳遞給計數器的構造函數。

>>> from itertools import chain, imap 
>>> from operator import itemgetter 
>>> from collections import Counter 
>>> words = 'happy', 'harpy', 'hasty' 
>>> counter = Counter(chain.from_iterable(imap(set, words))) 
>>> map(itemgetter(0), counter.most_common()) 
['a', 'h', 'y', 'p', 's', 'r', 't'] 
相關問題