Solucionado (ver solução)
Solucionado
(ver solução)
1
resposta

Problema em código para retornar o número de ocorrências de cada palavra em um texto. O que estou errando?

O texto utilizado para testar o código abaixo: https://easyupload.io/ahnrxo

    def ocorrencias(self):
        dic_palavras = {}
        cont = 0
        import string
        with open(arq) as f:
            for linha in f:
                for pal in linha.split():
                    for i in string.punctuation:
                        if i in pal:
                            pal = pal.replace(i,"")
                    pal = pal.lower()
                    if pal in dic_palavras:
                        cont+=1
                        dic_palavras[pal]=cont
                    else:
                        cont = 1
                        dic_palavras[pal] = cont
        print(dic_palavras)

A saída:

{'this': 2, 'is': 2, 'the': 2, 'most': 1, 'favourable': 1, 'period': 1, 'for': 2, 'travelling': 1, 'in': 2, 'russia': 1, 'they': 1, 'fly': 1, 'quickly': 1, 'over': 1, 'snow': 1, 'their': 1, 'sledges': 1, 'motion': 1, 'pleasant': 1, 'and': 2, 'my': 2, 'opinion': 1, 'far': 1, 'more': 1, 'agreeable': 1, 'than': 1, 'that': 3, 'of': 2, 'an': 1, 'english': 1, 'stagecoach': 1, 'cold': 1, 'not': 2, 'excessive': 1, 'if': 2, 'you': 3, 'are': 2, 'wrapped': 1, 'fursa': 1, 'dress': 1, 'which': 3, 'i': 4, 'have': 3, 'already': 1, 'adopted': 1, 'there': 2, 'a': 2, 'great': 1, 'difference': 1, 'between': 2, 'walking': 1, 'deck': 1, 'remaining': 1, 'seated': 1, 'motionless': 1, 'hours': 1, 'when': 3, 'no': 4, 'exercise': 1, 'prevents': 1, 'blood': 1, 'from': 1, 'actually': 1, 'freezing': 1, 'your': 2, 'veins': 1, 'ambition': 1, 'to': 2, 'lose': 1, 'life': 1, 'on': 2, 'postroad': 1, 'st': 1, 'petersburgh': 1, 'archangel': 1, 'shall': 4, 'depart': 1, 'latter': 1, 'town': 1, 'fortnight': 1, 'or': 2, 'three': 1, 'weeks': 1, 'intention': 1, 'hire': 1, 'ship': 1, 'can': 2, 'easily': 1, 'be': 1, 'done': 1, 'by': 1, 'paying': 1, 'insurance': 1, 'owner': 1, 'engage': 1, 'as': 2, 'many': 3, 'sailors': 1, 'think': 1, 'necessary': 1, 'among': 1, 'those': 1, 'who': 1, 'accustomed': 1, 'whalefishing': 1, 'do': 1, 'intend': 1, 'sail': 1, 'until': 1, 'month': 1, 'june': 1, 'return': 1, 'ah': 1, 'dear': 3, 'sister': 1, 'how': 1, 'answer': 1, 'question': 1, 'succeed': 1, 'months': 1, 'perhaps': 1, 'years': 1, 'will': 3, 'pass': 1, 'before': 1, 'may': 5, 'meet': 1, 'fail': 1, 'see': 1, 'me': 2, 'again': 8, 'soon': 1, 'never': 1, 'farewell': 1, 'excellent': 1, 'margaret': 1, 'heaven': 1, 'shower': 1, 'down': 1, 'blessings': 1, 'save': 1, 'testify': 1, 'gratitude': 1, 'all': 1, 'love': 1, 'kindness': 1}

O código não está contando adequadamente: Por exemplo: a saída diz que há 2 palavras for, mas na realidade há 6... O que estou fazendo errado?

1 resposta
solução!

Olá Edson,

O principal problema que eu vi nesse código é a utilização de um único contador para todas as palavras, assim sempre que adiciona uma palavra nova no dicionário o contador volta para 1 e atrapalha na contagem das próximas palavras.

Você pode fazer esse código sem utilizar um contador, apenas incrementando diretamente em cada item do dicionário:

if pal in dic_palavras:
    dic_palavras[pal] += 1
else:
    dic_palavras[pal] = 1