python count of different words with only one counter?

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 wanted it to work like this: no for must be able to read each letter of the given text and each letter increment according to the result of if . Let me give you an example: The counter always starts with a value of 1 for all letters. We read the word ola in the variable aleatorio the random number created is 0.4, that is, it should increment 1 to count . After that we should read the second word mundo and if, for example, aleatorio for 0.3 must increment 1 to count but the count is already 2, that is, increment will increment 3 and save. And that's not what you should do. I mean, do I need several counters? How do I do this?

    
asked by anonymous 16.12.2018 / 02:38

1 answer

1

Using this phrase:

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

Now we can use defaultdict to make a counter dictionary that stores an integer for each word - we have already set it 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 for that specific word directly:

for palavra in palavras:
    if random.random() < 0.5:
        contador[palavra] += 1
    
16.12.2018 / 13:29