首页 > 解决方案 > 如何从句子中计算相同的单词?

问题描述

我想问如何从句子中计算相同的单词(在 Python 中)。

举个例子,像这样的句子:“多么美好的一天。鸟儿在歌唱,孩子们在笑。”

我要提取的是: ['what':1, 'a':1, 'wonderful':1, 'dat':1, 'birds':1, 'are':2, 'singing':1, “孩子”:1,“笑”:1]

我在这里做了:

sent = "What a wonderful day. Birds are singing, children are laughing."
b = set([word.lower() for word in a])
c = list(b)

如果此代码不适合该工作,请告诉我。谢谢你。

标签: pythonstringcountword

解决方案


您可以为此使用counter和 re

import re
from collections import Counter
remove_punctutation = re.findall("[A-Za-z]+",sent)
print(dict(Counter(remove_punctutation)))
#{'What': 1,'a': 1,'wonderful': 1,'day': 1,'Birds': 1,'are': 2,'singing': 1,'children': 1,'laughing': 1}


推荐阅读