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

标签 python string list count word

这个问题在这里已经有了答案:





How to find the count of a word in a string?

(9 个回答)


去年关闭。




考虑

doc = ["i am a fellow student", "we both are the good student", "a student works hard"]
我有这个作为输入我只想打印整个列表中每个单词出现的次数:
例如学生出现 3 次所以
预期输出 学生=3,a=2,等等
我能够打印文档中的唯一单词,但无法打印出现的次数。这是我使用的功能:
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']
我得到这个作为输出我只想要unique_words的出现次数。请问我该怎么做?

最佳答案

您只需要使用 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()))
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
}
例如 count['student'] == 3 , count['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}

关于python计算字符串列表中的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62775131/

相关文章:

python - 用 Python 解析莎士比亚文本

python - 打印列表时的括号

python-3.x - 如何从两个不同的列表中删除重复项?

C# List<T> OrderBy float 成员

python - 在 openpyxl 条件格式公式中使用多个单元格

python - ElementTree 和使用 NameSpaces 查找

Java 字符串分割在 "\n"处失败

python - Google App Engine,使用 python 获取命名空间

python - 如何有条件地将文件包含在 Sphinx 'toctree' 中?

c# - 比较字符串相似度