Problem handling text files with python

2

I'm trying to make a game of gallows, and for that, I'm picking up lists of words and putting them in .txt format for Python to use in the game.

When picking up a list of names of people, there are some that come with parentheses after the name, and among these, plus some with equal sign between parentheses, for example:

  

Ana Beatriz (=)

This is due to the site from where I copied the names. He had some pointers, and he could not copy them without them coming together.

So, I created a code for Python to remove these unwanted characters for me:

entrada = open('Pessoas2.txt', 'r') # Cópia da lista de nomes que tenho
saida = open('Pessoas3.txt', 'w')   # Local onde as linhas editadas serão escritas

for linha in entrada:
    l = entrada.readline()
    l = l.replace('(', '').replace(')', '').replace('=', '')
    l = l.rstrip()
    saida.write(l)

entrada.close()
saida.close()

It was apparently okay, the code works. But he takes more things than I want. My original list has 200 names, and the new file only contains 100 names, meaning it simply erases names, and I do not know why. Could you help me?

    
asked by anonymous 01.05.2015 / 17:47

1 answer

1

This happens because the line is being read from the entrada variable, the correct one would be to get it from the linha variable. Your code should look like this:

entrada = open('Pessoas2.txt', 'r')
saida = open('Pessoas3.txt', 'w')

for linha in entrada:
    l = linha.rstrip()
    # substituindo o ")" por um nova linha
    l = l.replace('(', '').replace(')', '\n').replace('=', '') 

    saida.write(l)
entrada.close()
saida.close()

Another way to do this is to use the traslate method when instead of replace .

with open('Pessoas2.txt') as entrada, open('Pessoas3.txt', 'w') as saida:
    for linha in entrada:
        linha = linha.rstrip()
        linha = linha.translate({ ord('('): '', ord('='): '', ord(')'): '\n' })
        saida.write(linha)
    
01.05.2015 / 18:15