count how many times the loaded word from the txt file appears python [closed]

1

I need to make a program where I save a txt file, then open it and read it. So far so good. But I do not know how to show how many times each word of the open text appears.

Ex: The text appears the word mil 5 times, the word house 7 times and so on. How do I read what's inside the text, without having to create a list for it?

    
asked by anonymous 07.10.2017 / 14:15

1 answer

2

To tell a word you can do this:

palavra = 'casa'
with open('arquivo.txt') as f:
    ocorrencias = f.read().count(palavra)
print(ocorrencias) # num de vezes que a palavra aparece

If you want to tell all occurrences of all words:

from collections import Counter

with open('arquivo.txt') as f:
    ocorrencias = Counter(f.read().split())
print(ocorrencias) # num de vezes que as palavras aparecem

NOTE: In this last one, an explicit list is created when f.read().split() , although we do not give it away

    
07.10.2017 / 14:41