在列表PYTHON中计算单词的重复次数

2024-04-25 02:09:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个密码像:

s = "hello this is hello this is baby baby baby baby hello"
slist = s.split()
finallist = []
for word in slist:
    if len(word) >= 4:
          final = final + [word]

基本上这段代码用于获取列表并只放置一个包含4个以上字符的单词列表。

从这个列表中,我希望能够计算出同一个单词出现的次数,并将其保存到一个新列表中。所以就像[3,2,4]3是打招呼的时间,2是打招呼的时间,4是婴儿。


Tags: in密码hello列表foris时间this
3条回答
from collections import Counter
import re

reg = re.compile('\S{4,}')

s = "hello this is hello this is baby baby baby baby hello"
c = Counter(ma.group() for ma in reg.finditer(s))
print c

结果

Counter({'baby': 4, 'hello': 3, 'this': 2})

另外:

from collections import defaultdict
d = defaultdict(int)

s = "hello this is hello this is baby baby baby baby hello"

for w in s.split():
    if len(w)>=4:
        d[w] += 1

print d

您只需使用slist中的count方法。

我想你可以用口述来更好地控制

s = "hello this is hello this is baby baby baby baby hello"
slist = s.split()
finaldict = {}
for word in slist:
    if len(word) >= 4 and not finaldict.get(word):
          finaldict[word] = slist.count(word)

现在,如果需要值列表,请执行以下操作:finallist = finaldict.values()

collections.Counter显然是您的朋友(除非您需要按特定顺序排序的输出)。把它和生成器理解结合起来,生成所有长度为4的单词,你就是黄金。

from collections import Counter

Counter(w for w in s.split() if len(w) >= 4)

如果需要按元素的第一次出现顺序排列元素,请使用有序字典:

from collections import OrderedDict

wc = OrderedDict()
for w in s.split():
    if len(w) >= 4:
        wc[w] = wc.get(w, 0) + 1

相关问题 更多 >