python - 如何从句子中计算相同的单词?
问题描述
我想问如何从句子中计算相同的单词(在 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)
如果此代码不适合该工作,请告诉我。谢谢你。
解决方案
您可以为此使用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}
推荐阅读
- arduino - 更改 I2C 引脚分配时 Qwiic 实时时钟模块不工作
- python - Is there a python module that covers all html entities?
- html - 如果我将 PWA 添加到主屏幕,我可以从本地存储中获取当前数据吗?
- svn - 无法找到 svn 忽略属性以取消忽略文件
- php - 如何将特定的键值元素保留在数组中并删除其余部分?
- django - 构建自定义视图以向特定用户授予权限(不使用 ADMIN)
- python - 以 10 为基数的 int() 的无效文字:“字符串名称”
- node.js - 我想在 mongodb 中创建一个包含数组字段的文档
- oauth-2.0 - 如何使用先前获取的不透明格式的访问令牌获取 jwt 格式的访问令牌
- go - 将 map[string][]string 转换为 []map[string]interface{}