Word processing

Asked

Viewed 262 times

0

I have the following scenario: I have a variable with a text inside. I separate this text by words inside a array, With this I need to validate how many times each word appears in the text. I managed to do, but there’s another detail, I need to run the whole list without going through a word I’ve already caught the count.

Ex: "In a nest of mafagafos there are seven mafagafinhos. When mafagafa Gafa, gafam the seven mafagafinhos."

In this case I can not pass the code without repeating the "mafagafinhos". What I do?

  • 2

    You can post the snippet of your code that makes this word count?

1 answer

1


An example of word counter could be done as follows:

import sys
text = "Num ninho de mafagafos há sete mafagafinhos. Quando a mafagafa gafa, gafam os sete mafagafinhos."
wordcount={}
for word in text.split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
for key in wordcount.keys():
    print("%s %s " %(key , wordcount[key]))
  • 1

    Behold that.

  • 2

    Didactically the answer is ok to understand the logic, but it should be stressed that there are better ways to do this. Example of three different but more 'pythonic' ways: http://ideone.com/A2zCH9

Browser other questions tagged

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