Problem comparing strings and string being broken in two python rows

3

I was creating a game that scrambles words, and the user has 6 attempts to guess what the word is. I'll put the code here:

import random

def main():
    while True:
        input('Presisone enter para sortear uma nova palavra.')
        palavra_oculta, dica = EscolhePalavra()
        palavra_embaralhada = EmbaralhaPalavra(palavra_oculta)
        palavra_embaralhada = palavra_embaralhada.lower()
        palavra_oculta = palavra_oculta.lower()
        tentativas = 6
        while tentativas != 0:
            print('\nA palavra embaralhada é: %s'%palavra_embaralhada)
            print('A dica é: %s'%dica)
            print('Você ainda tem %d tentativas.'%tentativas)
            palpite = input('Digite seu palpite: ')
            if palpite == palavra_oculta:
                print('Parabéns, você acertou!!!')
                break
            else:
                print('Ainda nao, tente novamente!')
                tentativas -= 1
        if tentativas == 0:
            print('Você perdeu! a palavra correta era %s.'%palavra_oculta)
        else:
            print('Parabéns, você acertou a palavra!!!')

def EscolhePalavra(): #Essa função está funcionando normalmente, a usei em outro jogo.
    lista_arquivos = {'Animais.txt' : 'Animal', 'Frutas.txt' : 'Fruta',
                      'Objetos.txt' : 'Objeto', 'Pessoas.txt' : 'Pesssoa',
                      'Profissões.txt' : 'Profissão'}
    arquivo_escolhido = random.choice(list(lista_arquivos.keys()))
    palavra = random.choice(open(arquivo_escolhido).readlines())
    dica = lista_arquivos[arquivo_escolhido]
    return(palavra, dica)

def EmbaralhaPalavra(palavra):
    palavra = list(palavra)
    random.shuffle(palavra)
    palavra = ''.join(palavra)
    return palavra

if __name__ == '__main__':
    main()

Let's face the problems: First, with the word scrambled. For some reason I still do not know which one, by giving print to palavra_embaralhada , most of the time it gets broken into two lines. I have already tried to give a print on a separate line in the code, but the problem persists.

The second is that the comparison between the string written by the user stored in the variable palpite , and the palavra_oculta almost always goes wrong. I was only able to hit once. As much as I type the correct word, the program considers it to be two different strings . What I have to do?

    
asked by anonymous 04.05.2015 / 14:50

1 answer

2
  

First, with the word scrambled. For some reason that has not yet   I know which, when giving a print in word_embarse, most of the times   it gets broken in two lines. I've already tried to print it on a   line in the code, but the problem persists.

  • The problem occurs in the EmbaralhaPalavra function, assuming that the palavra_oculta variable has the Bar value, when using list , the value returned is a list containing ['B', 'a', 'r', '\n'] , and when doing the random.shuffle , the following happens (may vary) : ['a', 'B', '\n', 'r'] , ie the reason for line break , is due to new line a> that is created using list . To correct this, you will need to remove the new line before doing the shuffle. One way to do this is to use the rstrip method, there are also other ways.

    def EmbaralhaPalavra(palavra):
       palavra = palavra.rstrip()
       palavra = list(palavra)
       random.shuffle(palavra)
       palavra = ''.join(palavra)
       return palavra
    
  

The second is that the comparison between the string written by the user   stored in the guess variable, and the search_word almost always exits   wrong. I only managed to hit it once. As much as I type the   word, the program considers it to be two strings   many different. What do I have to do?

  • Same problem . Now in the EscolhePalavra function, in the line where you open the file and read the lines:

    palavra = random.choice(open(arquivo_escolhido).readlines())
    

    readlines() returns everything, including new lines, when comparing: if palpite == palavra_oculta.. , is compared: Bar with Bar\n . To resolve this, you can use the same solution that was used in the first problem, or use the str.splitlines() instead of readlines() , this will eliminate line breaks .

     
    def EscolhePalavra(): 
       lista_arquivos = {'Animais.txt' : 'Animal', 
                         'Frutas.txt' : 'Fruta',
                         'Objetos.txt' : 'Objeto', 
                         'Pessoas.txt' : 'Pesssoa',
                         'Profissões.txt' : 'Profissão'}
       arquivo_escolhido = random.choice(list(lista_arquivos.keys()))
       linhas = open(arquivo_escolhido).read().splitlines()
       palavra = random.choice(linhas)
       dica = lista_arquivos[arquivo_escolhido]
       return(palavra, dica)
    

    The comparison of strings in Python is case-sensitive , which can affect the result of the game, of the variable palavra_oculta with the value of the variable palpite , which may contain uppercase letters, also use the lower() method in palpite .

05.05.2015 / 08:18