Python-计算单词列表中的每个字母

时间:2011-06-15 04:35:33

标签: python algorithm collections dictionary

所以我有一个单词列表`wordList = list()。'现在,我正在使用此代码计算整个列表中每个单词中的每个字母

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

但是,我希望它的计算方式不同。我希望函数能够从列表中的所有单词中找到最常见的字母,但只能通过计算每个单词的每个字母一次(忽略一些单词可以具有相同字母的多个副本的事实)。

例如,如果列表中包含“happy,harpy and hasty”,那么快乐中的两个p应该只计算一次。因此该函数应返回最高频率字母的列表(按顺序),而不重复计算。在上面的例子中,它将是'h,a,p,y,r,s“

7 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:6)

添加set来电:

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

答案 2 :(得分:3)

itertools中使用迭代器组合器的另一种方法:

import collections
import itertools

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

答案 3 :(得分:2)

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

答案 4 :(得分:2)

您可以使用for消除updatefrom 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']

{{1}}

答案 5 :(得分:1)

这会从每个单词创建一个集合,并将它们传递给Counter。

的构造函数
>>> 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']

答案 6 :(得分:0)

import collections

cnt = collections.Counter('happy harpy hasty').keys()

cnt = list(cnt)

print(cnt)
相关问题