python计算字符串列表中的单词数

tac*_*yon 4 python string list count cpu-word

考虑

doc = ["i am a fellow student", "we both are the good student", "a student works hard"]
Run Code Online (Sandbox Code Playgroud)

我有这个作为输入我只想打印整个列表中每个单词出现的次数:

例如 student 出现 3 次所以 预期输出student=3, a=2, etc

我能够打印文档中的唯一单词,但无法打印出现的次数。这是我使用的功能:

def fit(doc):    
    unique_words = set() 
    if isinstance(dataset, (list,)):
        for row in dataset:
            for word in row.split(" "): 
                if len(word) < 2:
                    continue
                unique_words.add(word)
        unique_words = sorted(list(unique_words))
        return (unique_words)
doc=fit(docs)

print(doc)

['am', 'are', 'both', 'fellow', 'good', 'hard', 'student', 'the', 'we', 'works']
Run Code Online (Sandbox Code Playgroud)

我得到这个作为输出我只想要unique_words的出现次数。请问我该怎么做?

Ric*_*cco 7

您只需要使用Counter,您将通过使用一行代码来解决问题:

from collections import Counter

doc = ["i am a fellow student",
       "we both are the good student",
       "a student works hard"]

count = dict(Counter(word for sentence in doc for word in sentence.split()))
Run Code Online (Sandbox Code Playgroud)

count 是你想要的字典:

{
    'i': 1,
    'am': 1,
    'a': 2,
    'fellow': 1,
    'student': 3,
    'we': 1,
    'both': 1,
    'are': 1,
    'the': 1,
    'good': 1,
    'works': 1,
    'hard': 1
}
Run Code Online (Sandbox Code Playgroud)

例如count['student'] == 3count['a'] == 2等等。

在这里使用split()而不是split(' '):很重要:这样你就不会在count. 例子:

>>> sentence = "Hello     world"
>>> dict(Counter(sentence.split(' ')))
{'Hello': 1, '': 4, 'world': 1}
>>> dict(Counter(sentence.split()))
{'Hello': 1, 'world': 1}
Run Code Online (Sandbox Code Playgroud)