newbiecoder
newbiecoder

Reputation: 21

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.

Upvotes: 0

Views: 880

Answers (1)

Mr. Discuss
Mr. Discuss

Reputation: 437

I think string.count() should do here. 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'))

Upvotes: 3

Related Questions