Return word media in a dictionary from another function

Asked

Viewed 342 times

0

I need a function that receives the result of a word counting function and based on these values, this function calculates the average of how many times a word appears in the text, stores that average in a dictionary and returns the dictionary with that value.

example:

Parâmetro: ‘{‘três’: 2, ‘pratos’:1}
Retorno: {'três': 0.25, 'pratos': 0.125}

I was able to do the function counts words, but I’m having difficulty calculating the average in which each word appears.

def conta_palavras(x):
    palavras = {}

    for palavra in x.split():
        if palavra in palavras:
            palavras[palavra] += 1
        else:
            palavras[palavra] = 1

    return palavras

def conta_media_palavras(x):
    palavras = conta_palavras
    maximo = 0
    freq = ''
    for palavra in palavras:
        if palavras[palavra] > maximo:
            maximo = palavras[palavra]
            freq = palavra
  • Your question is not well formulated and we still lack the data to better understand the situation. What text are you talking about before displaying the parameter?. Anyway, try using the function count() to count the words.

  • Victor, as Whoismatt said, your question is really poorly worded, so try to edit it and put in some more presentable code so we can help you. The more detailed the question, the easier it is to get help.

1 answer

1

In function conta_media_palavras you need to call the function contar_palavras. The way you did just set a new name for the same function, you didn’t call it.

Instead of palavras = conta_palavras you must do palavras = conta_palavras(x). Parentheses indicate that it will be a function call passing the value of x as a parameter.

After that you will have to count the amount of words that exists in the initial sentence. You can do this from the dictionary itself returned by contar_palavras:

quantidade = sum(item[1] for item in palavras.item())

Or straight from the phrase in x:

quantidade = len(x.split())

The result should be the same. With the amount of words, just iterate over your dictionary and divide the word frequency by the amount, possibly returning this in another dictionary:

def conta_media_palavras(x):
    palavras = contar_palavras(x)
    quantidade = len(x.split())
    media = {}

    for palavra, frequencia in palavras.items():
        media[palavra] = frequencia / quantidade

    return media

You can use Dict comprehension to rewrite the function:

 def conta_media_palavras(x):
    palavras = contar_palavras(x)
    quantidade = len(x.split())
    media = {palavra: frequencia / quantidade for palavra, frequencia in palavras.items()}

    return media

And to improve function contar_palavras read about collections.defaultdict and collections.Counter.

Browser other questions tagged

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