python - 如何在python中拆分文本计数字符串列表中的出现次数
问题描述
def find_occurrences(text, itemsList):
count = dict()
words = text.split()
return count;
assert find_occurrences(['welcome to our Python program', 'Python is my favourite language!', 'I love Python'], 'Python')
assert find_occurrences(['this is the best day', 'my best friend is my dog'], 'best')
我必须编写代码来帮助我计算一个单词在句子列表中出现的次数。
我正在尝试拆分文本,但它不允许我这样做。我想我需要找到一种方法来阅读句子然后拆分它,但我想不出一种方法来做到这一点。如果有人可以帮助或指出我正确的方向,那将很有帮助。
我可能可以从那里弄清楚其余的。
解决方案
我认为string.count()
应该在这里做。只需遍历输入列表:
def find_occurrences(text, itemsList):
occurs = 0
for i in text:
occurs += i.count(itemsList)
return occurs
print(find_occurrences(['welcome to our Python program', 'Python is my favourite language!', 'I love Python'], 'Python'))
print(find_occurrences(['this is the best day', 'my best friend is my dog'], 'best'))
推荐阅读
- visual-studio - 没有开发人员模式/开发人员许可证无法旁加载 Win10 UWP 应用程序
- r - 如何重新排序热图树状图中的行?
- php - PHP 脚本:在 mySQL 数据库中写入 IP 地址。这样做两次是行不通的
- flutter - 我在没有 Android Studio 的 ubuntu 上安装了颤振,它一直在工作,然后突然给我一个错误,为什么?
- javascript - Socket io - 错误的套接字地址调用
- c# - 从 Post Request Angular/.NET Core 获取数据
- php - php从字符串中删除重复项
- python - 有没有办法循环遍历方法和更改对象名称?
- c# - 在没有任何日志的编辑器上启动时卡住(可能是因为时间字符串解析)
- angular - 使用 ionic/angular 上的 firebase 更新自动登录菜单