考虑
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']
我得到这个作为输出,我只想要唯一的单词出现的次数。请问我该怎么做
使用
导致
说明:首先使用
join
创建一个字符串,并在带有split
的空格中拆分它,以获得单个单词的列表。使用Counter
计算每个单词的外观您只需要使用
Counter
,就可以通过使用一行代码来解决问题:count
是您想要的字典:例如{},{}等等
在这里,使用
split()
而不是split(' ')
是很重要的:这样你就不会在count
中有一个“空”字了。例如:谢谢你的提问。 这是我的答案。因为我是初学者。请接受我对任何错误的道歉。谢谢你
相关问题 更多 >
编程相关推荐