Python dictionary

Asked

Viewed 85 times

1

The code below should count the words of the text and at the end show the amount of times each word appears in the text.

I’m using the anaconda’s Spyder (Python 3.7).

texto = """Caso tenha o estigma de enfrentar a situação com a mente fria, a situação não se agravara.
 """

def converte_texto(texto):
    pontuacao = ['.',',',':',';','!','?','"','(', ')']
    novo_texto = ''.join(c for c in texto if c not in pontuacao).upper()
    lista = novo_texto.split()
    return lista

print(texto)
print(converte_texto(texto))


def palavras(texto):

    palavras = converte_texto(texto)

    contagem = dict()

    for n in palavras : 
        contagem[n] = contagem.get(n, 0) + 1

        return(contagem)

print( palavras(texto) )

At the end it only shows the result with the first word, (which is not correct). It was right to count even with only one word.

Upshot:

['CASO', 'TENHA', 'O', 'ESTIGMA', 'DE', 'ENFRENTAR', 'A', 'SITUAÇÃO', 'COM', 'A', 'MENTE', 'FRIA', 'A', 'SITUAÇÃO', 'NÃO', 'SE', 'AGRAVARA']
{'CASO': 1}

1 answer

0


The problem is the identation of return(contagem). You put him inside the for, then the loop only happens once and the function returns. Indent the indentation of this line that the problem will be solved. Below are some changes I made to your code:

texto = 'Caso tenha o estigma de enfrentar a situação com a mente fria, a situação não se agravara.'

def converte_texto(texto):
    pontuacao = ['.',',',':',';','!','?','"','(', ')']
    novo_texto = ''.join(c for c in texto if c not in pontuacao).upper()
    lista = novo_texto.split()
    return lista

def palavras(texto):
    palavras = converte_texto(texto)
    contagem = dict()

    for palavra in palavras : 
        contagem[palavra] = contagem.get(palavra, 0) + 1

    return contagem

print(palavras(texto))
  • Very, thank you helped a lot without wanting to abuse and what would it be like to add a word classifier that has more repetitions?? in case it would be a large text.

  • If the answer was helpful and solved your problem, mark it as the best answer. I don’t understand what you mean by classifier.

  • I marked it as the best answer, thank you, so I’m hoping that in the end it will classify the words from major to minor, (example: 'Situation: 5', 'Mind: 3', 'face: 2') and so on.

Browser other questions tagged

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