Leave each word in a row (Text file) - Python

Asked

Viewed 394 times

1

Good afternoon gentlemen! I have a text file with several lines of text. I would like to manipulate it to the point of leaving one word per line. In this way I would ignore some characters such as: comma, period, exclamation point, question mark etc. I would leave only the words. Could someone help me?

  • 1

    I could give an example of how your text file is and how I would like it to look after the process?

3 answers

1

A line break in text is nothing more than a special character " n". In python, there is the 'replace' method for strings, which is used like this

"blabla".replace('a' , 'e') 

resulting in the string "bleble".

'a’s have been replaced by 'e’s. You can replace a character (or a string) with nothing, too.

"vígula,".replace("," , "")

resulting in the string "comma".

Or:

"coisa".replace("coisa" , "nada")

resulting in the string "nothing".

And finally:

"várias palavras separadas por espaço".replace(" " , "\n")

resulting "several npalavras nseparadas npor nespaço".

The special character " n", as stated, will be displayed as a new line, separating the words into different lines.

  • Thanks my dear! God double add.

  • If the answer is correct, @Eulerricardo , don’t forget to reward our friend with " ", right at the top left of the answer!

0

You can use regular expressions to split words. This makes it easy to ignore special characters such as commas and dots. The code gets simpler too:

import re

with open('seu_arquivo.txt') as arquivo:
    palavras = (palavra for linha in arquivo 
        for palavra in re.findall(r'\w+', linha))
    for palavra in palavras:
        print(palavra)

In this case the expression r'\w+' will take all the grouped letters, and return each group of letters (word)

0

One way would be to concatenate variables.

An example:

p1 = "Uma"
p2 = "Palavra"
p3 = "Qualquer"
print (p1 + " " + p2 + " " + p3)
  • but I need to read the iury file

  • Sorry man, I thought that was it because I’m also learning Python.

  • Relex brother... your help was quite a start

Browser other questions tagged

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