Search code examples
pythonfrequency

finding occurrences in Multiple sentences


I'm new to python however after scouring the internet and going back over my study, I cannot seem to find how to find duplicates of a word within multiple sentences. my aim is to define how many times the word python occurs within these strings. I have tried the split() method and count.(python) and even tried to make a dictionary and word_counter which initially I have been taught to do as part of the basics however nothin in my study has shown me anything similar to this before. i need to be able to display the frequency of the word. python occurs 4 times. any help would be very appreciated

python_occurs = ["welcome to our Python program", "Python is my favorite language!", "I am afraid of Pythons", "I love Python"]


Solution

  • A straight-forward approach is to iterate over every word using split. For each word, it's converted to lowercase and the number of times "python" occurs in it is counted using count.

    I guess the reason for you approach not working might be that you forgot to change the letters to lowercase.

    python_occurs = ["welcome to our Python program", "Python is my favorite language!", "I am afraid of Pythons", "I love Python"]
    count = 0
    for sentence in python_occurs:
        for word in sentence.split():
            # lower is necessary because we want to be case-insensitive
            count += word.lower().count("python")