Search code examples
pythonlistcounterwords

How to calculate the number of times a word is in a text


I'm new in python and i don't know how to solve this: Write a function that calculates the number of times a word appears in a text. This is my code so far but i'm stuck. I think i need to find a way to split the text in words but it's in a list so i can't do it in this way.

def searcher(file):
    f = open(file,"r")
    word = raw_input("Write your word: ")
    text = f.readlines()
    text1 = text.split()
    counter = 0
    for x in text1:
        if x == word:
            counter = counter +1
    print counter

Thanks in advance


Solution

  • Use collections.Counter passing in each line split in individual words.

    s = "foo foo foobar bar"
    from collections import Counter
    print Counter(s.split())
    Counter({'foo': 2, 'foobar': 1, 'bar': 1})
    
    def searcher(file):
        c = Counter()
        word = raw_input("Write your word: ")
        with open(file,"r") as f:
           for line in f:
               c.update(line.lower().rstrip().split())
        return c.get(word)