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

Asked

Viewed 3,550 times

0

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

Ex: The text appears the word thousand five times, the word house seven times and etc. How do I read what is inside the text, without having to create a list for it?

  • You only want to count how many times a specific word appears in the file?

  • 2

    @Andersoncarloswoss thought so, too, but I think this one might go down a less laborious path. The other entailed the opening of two files and processing of the data between them

  • car home chocolate dish scoop mat plate plate chocolate from Collections import Counterwith open('/Users/DIGITAL/Desktop/Python/test.txt') as f: occurrences = Counter(f.read().split()) print(occurrences) The words that are in the text were those, but at the time of sorting, I need it to appear in ascending order, ta appearing like this: choclocate 3 vzs, box 2.. and I need it to appear backwards, from the smallest to the largest

  • Hello I think you should ask a new question independent of this, that part is not part and not at all comtemplada in this question/ answer. You’d better erase what you’ve done since it’s an exclusive space for answers. Welcome to Stackoverflow

1 answer

2


To tell a word you can do so:

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

Done this, if you want to count 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: this last one creates an explicit list when f.read().split(), even though we don’t notice her

Browser other questions tagged

You are not signed in. Login or sign up in order to post.