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

2024-04-27 00:07:38 发布

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

考虑

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

我得到这个作为输出,我只想要唯一的单词出现的次数。请问我该怎么做


Tags: thedocam单词studentarewordwe
3条回答

使用

from collections import Counter
Counter(" ".join(doc).split())

导致

Counter({'i': 1,
         'am': 1,
         'a': 2,
         'fellow': 1,
         'student': 3,
         'we': 1,
         'both': 1,
         'are': 1,
         'the': 1,
         'good': 1,
         'works': 1,
         'hard': 1})

说明:首先使用join创建一个字符串,并在带有split的空格中拆分它,以获得单个单词的列表。使用Counter计算每个单词的外观

您只需要使用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
}

例如{},{}等等

在这里,使用split()而不是split(' ')是很重要的:这样你就不会在count中有一个“空”字了。例如:

>>> sentence = "Hello     world"
>>> dict(Counter(sentence.split(' ')))
{'Hello': 1, '': 4, 'world': 1}
>>> dict(Counter(sentence.split()))
{'Hello': 1, 'world': 1}

谢谢你的提问。 这是我的答案。因为我是初学者。请接受我对任何错误的道歉。谢谢你

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

p = doc[0].split() #first list

p1 = doc[1].split() #second list

p2 = doc[2].split() #third list

f1 = p + p1 + p2

j = len(f1)-1

n = 0

while n < j:

    print(f1[n],"is found",f1.count(f1[n]), "times")

    n+=1

相关问题 更多 >