Problem handling text files with python

Asked

Viewed 1,015 times

2

I’m trying to make a hangman game, and for that, I’m taking word lists and putting them in files in format .txt for Python to use in the game.

When picking up a list of names of people, have some that comes with parentheses after the name, and among these, more some with equal sign between the parentheses, for example:

Ana Beatriz ( = )

This is due to the site where I copied the names. He had some indications, and could not copy without them come 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 all right, the code works. Only it takes away more things than I want. My original list has 200 names, and the new file contains only 100 names, that is, it simply erases names, and I don’t know why. Could you help me?

1 answer

1


This is because the line is being read from the variable entrada, the correct one would be to obtain it from the variable linha. 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 substitution is to use the method traslate 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)
  • 1

    Thank you very much. I only made a modification because he wasn’t breaking lines into names that didn’t have those characters that I wanted to remove. So instead of replacing the ')' for \n, I left as was and added a saida.write('\n') at the end of the loop.

Browser other questions tagged

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