簡體   English   中英

Python-計算單詞列表中的每個字母

[英]Python- Count each letter in a list of words

所以我有一個單詞列表“wordList = list()”。 現在,我正在使用此代碼計算整個列表中每個單詞中的每個字母

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

但是,我希望它以不同的方式計算。 我希望 function 從列表中的所有單詞中找到最常見的字母,但只能通過對每個單詞的每個字母計數一次(忽略某些單詞可以有同一個字母的多個副本的事實)。

例如,如果列表包含“happy, harpy and hasty”,那么happy 中的兩個p 應該只計算一次。 所以 function 應該返回一個頻率最高的字母列表(按順序),而不需要重復計算。 在上述情況下,它將是“h,a,p,y,r,s”

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

添加set調用:

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

itertools中使用迭代器組合器的另一種方法:

import collections
import itertools

cnt = collections.Counter(itertools.chain.from_iterable(itertools.imap(set, wordList)))
cnt = Counter()
for word in wordList:
    lSet = set(word)
    for letter in lSet:
        cnt[letter] +=1             

您可以使用update消除for ,它從可迭代(在本例中為字符串)更新計數:

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']

這會從每個單詞創建一個集合並將它們傳遞給 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']
import collections

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

cnt = list(cnt)

print(cnt)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM