1

Seja o texto abaixo:

This is the most favourable period for travelling in Russia.  They fly
quickly over the snow in their sledges; the motion is pleasant, and,
in my opinion, far more agreeable than that of an English stagecoach.
The cold is not excessive, if you are wrapped in furs--a dress which
I have already adopted, for there is a great difference between walking
the deck and remaining seated motionless for hours, when no exercise
prevents the blood from actually freezing in your veins.  I have no
ambition to lose my life on the post-road between St. Petersburgh
and Archangel. I shall depart for the latter town in a fortnight
or three weeks; and my intention is to hire a ship there, which can
easily be done by paying the insurance for the owner, and to engage
as many sailors as I think necessary among those who are accustomed
to the whale-fishing.  I do not intend to sail until the month of June;
and when shall I return?  Ah, dear sister, how can I answer this question?
If I succeed, many, many months, perhaps years, will pass before you
and I may meet.  If I fail, you will see me again soon, or never.
Farewell, my dear, excellent Margaret.  Heaven shower down blessings
on you, and save me, that I may again and again testify my gratitude
for all your love and kindness.

Gostaria de criar uma lista de palavras a partir do texto e exibir a frequência da ocorrência de cada uma. Achei na internet o código abaixo que funciona mas não entendi:

def PegaPalavras(texto):

       return ''.join((c if c.isalnum() else ' ') for c in texto).split()

Tentei reescrevê-lo de forma mais simples mas não consegui:

def PegaPalavras(texto):
    palavras = []

    for c in texto:
        if c.isalnum():
           c=c
           palavras.append("".join(c).split())
        else:
           c =" "
           palavras.append("".join(c).split())


    return palavras

Como reescrever o primeiro código de forma mais explícita (sem ser em apenas uma linha), de forma a facilitar o seu entedimento? Alguma outra solução?

0

2 Respostas 2

2

Você pode usar a função re.finditer do módulo de regex nativo do Python.

Usando o padrão \w+ em strings unicode você casará com 1 ou mais caracteres que devem fazer parte de uma palavra em unicode (isso seria de a-z, A-Z, 0-9, _, e os zilhões de variações que devem existir no Unicode). Veja a documentação.

Dessa maneira você pode criar um iterador que, a medida que vai lendo a string já vai retornando palavra por palavra.

Por exemplo:

def get_palavras(string):
    yield from re.finditer(r'\w+', string)

Um exemplo completo ficaria:

import re


def get_palavras(string):
    yield from re.finditer(r'\w+', string)


texto = """This is the most favourable period for travelling in Russia.  They fly
quickly over the snow in their sledges; the motion is pleasant, and,
in my opinion, far more agreeable than that of an English stagecoach.
The cold is not excessive, if you are wrapped in furs--a dress which
I have already adopted, for there is a great difference between walking
the deck and remaining seated motionless for hours, when no exercise
prevents the blood from actually freezing in your veins.  I have no
ambition to lose my life on the post-road between St. Petersburgh
and Archangel. I shall depart for the latter town in a fortnight
or three weeks; and my intention is to hire a ship there, which can
easily be done by paying the insurance for the owner, and to engage
as many sailors as I think necessary among those who are accustomed
to the whale-fishing.  I do not intend to sail until the month of June;
and when shall I return?  Ah, dear sister, how can I answer this question?
If I succeed, many, many months, perhaps years, will pass before you
and I may meet.  If I fail, you will see me again soon, or never.
Farewell, my dear, excellent Margaret.  Heaven shower down blessings
on you, and save me, that I may again and again testify my gratitude
for all your love and kindness."""

for match in get_palavras(texto):
    print(f"texto[{match.start()}:{match.end()}]: {match[0]}")

E a saída:

texto[0:4]: This
texto[5:7]: is
texto[8:11]: the
texto[12:16]: most
texto[17:27]: favourable
...
texto[1247:1250]: all
texto[1251:1255]: your
texto[1256:1260]: love
texto[1261:1264]: and
texto[1265:1273]: kindness

Veja funcionando no Repl.it

Na documentação do objeto do tipo Match, você pode ver quais métodos e atributos você pode ler a cada iteração (além de start, end e __getitem__ demonstrados no exemplo).

1

Dê uma olhada nesse link:

# Open the file in read mode 
text = open("sample.txt", "r") 

# Create an empty dictionary 
d = dict() 

# Loop through each line of the file 
for line in text: 
    # Remove the leading spaces and newline character 
    line = line.strip() 

    # Convert the characters in line to  
    # lowercase to avoid case mismatch 
    line = line.lower() 

    # Split the line into words 
    words = line.split(" ") 

    # Iterate over each word in line 
    for word in words: 
        # Check if the word is already in dictionary 
        if word in d: 
            # Increment count of word by 1 
            d[word] = d[word] + 1
        else: 
           # Add the word to dictionary with count 1 
            d[word] = 1

# Print the contents of dictionary 
for key in list(d.keys()): 
    print(key, ":", d[key]) 

Este código acima é generico e não desconsidera pontuações.. Para desconsiderar a pontuação, voce pode fazer uma regrinha para cada uma da pontuacao, por exemplor: palavra.replace("!", ""), ou algo mais generico como algo do tipo:

import re
string_nova = re.sub(u'[^a-zA-Z0-9áéíóúÁÉÍÓÚâêîôÂÊÎÔãõÃÕçÇ: ]', '', string_velha.decode('utf-8'))
3
  • Obrigado! Conseguiria me explicar o codigo -> return ''.join((c if c.isalnum() else ' ') for c in texto).split()
    – Ed S
    9/12/2019 às 14:10
  • o seu codigo nao ignora a pontuação...
    – Ed S
    9/12/2019 às 14:12
  • Ainda nao consegui dar uma olhada nesse codigo.. Quanto à pontuacao, adicionei na resposta 9/12/2019 às 14:28

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .