python Count of different words with only one counter?

Asked

Viewed 213 times

0

I have this code:

palavras = dataClean.split()
count = 1

for palavra, frequencia in palavras:
    aleatorio = random.uniform(0.0, 1.0)
    if aleatorio < 0.5:
        count += 1

    contProb[palavra] = count
    count = 0

print(contProb)

For example, for this txt:

olá mundo olá mundo adeus

So I’d like it to work this way: no for shall be able to read each letter of the given text and to increase each letter according to the result of if. Let me give you an example: The counter always starts with the value 1 for all letters. We read the word ola in the variable aleatorio the created Random number is 0.4, that is, you must increment 1 to count. After that we should read the second word mundo and if, for example, aleatorio is 0.3 shall increment 1 to count but Count is already 2, that is, incrementing will increase 3 and save. And that is not what you should do. I mean, do I need multiple counters? How do I do this

  • Friend, please, edit your question and add an example how the result would look for this txt you passed olá mundo olá mundo adeus; What do you want to end up with? Something like {'olá': 3, 'mundo': 2, 'adeus': 1} ?

1 answer

1


Using that phrase:

frase = "olá mundo olá mundo adeus"
palavras = frase.split()

Now we can use the defaultdict to make a counter dictionary that stores an integer number for each word - we already set to start with the value 1 for all words:

import collections
contador = collections.defaultdict(lambda: 1)

For each word, if the draw is positive, increment the counter of that specific word directly:

for palavra in palavras:
    if random.random() < 0.5:
        contador[palavra] += 1
  • Because it is @nosklo. You are absolutely right, I confused everything. I will edit the question right now. I appreciate your help.

  • @Walt057 edited the answer

Browser other questions tagged

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