简体   繁体   English

如何拆分文本 python 计算字符串列表中的出现次数

[英]How to split text in python count number of occurrences in a list of strings

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')

I have to write code that will help me count the number of occurrences of a word inside a list of sentences.我必须编写代码来帮助我计算一个单词在句子列表中出现的次数。

I am trying to split the text, but it will not allow me to.我正在尝试拆分文本,但它不允许我这样做。 I think I need to find a way to read the sentence and then split it, but I am unable to think of a way to do so.我想我需要找到一种方法来阅读句子然后将其拆分,但我想不出这样做的方法。 If anyone can help or point me in the right direction that would be helpful.如果有人可以帮助或指出正确的方向,那将很有帮助。

I probably could figure out the rest from there.我可能可以从那里算出 rest。

I think string.count() should do here.我认为string.count()应该在这里做。 Just iterate through the input list:只需遍历输入列表:

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'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM