首页 > 解决方案 > 如何在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')

我必须编写代码来帮助我计算一个单词在句子列表中出现的次数。

我正在尝试拆分文本,但它不允许我这样做。我想我需要找到一种方法来阅读句子然后拆分它,但我想不出一种方法来做到这一点。如果有人可以帮助或指出我正确的方向,那将很有帮助。

我可能可以从那里弄清楚其余的。

标签: pythonlistassert

解决方案


我认为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'))

推荐阅读