我为什么要获得额外的" *"在我的python应用程序的某些行上?

时间:2014-09-03 14:43:02

标签: python

我被要求进行A Level计算以创建基于文本的刽子手游戏。出于某种原因,当显示“guessword”时,它在末尾包含一个额外的字符,这个字符无法解决,因此使游戏无法取胜。这只发生在少数情况下,并非列表中的每个单词都有这个附加字符。

这是python代码:

import random

class Hangman():

def Playing(self):

    category = raw_input("Please select a category from; EuroCapitals; PremTeams; FruitAndVeg")
    again = True
    while again:

        guessword = open(category + ".txt", "r").readlines()[random.randint(0,9)]
        board = "*" * (len(guessword) - 1)
        alreadySaid = set()
        mistakes = 7

        print(" ".join(board))

        guessed = False
        while not guessed and mistakes > 0:

            whatplayersaid = raw_input("Guess a letter: ")

            if whatplayersaid in guessword:
                alreadySaid.add(whatplayersaid)
                board = "".join([char if char in alreadySaid else "*" for char in guessword])
                if board == guessword:
                    guessed = True
            else:
                mistakes -= 1
                print("Nope.", mistakes, "mistakes left.")

            print(" ".join(board))

        again = (input("Again [y/n]: ").lower() == 'y')


Hangman().Playing()

“EuroCapitals.txt”中的单词列表如下:

london
paris
madrid
berlin
moscow
rome
amsterdam
bern
zagreb
stockholm

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

很可能它是文件中的\n字符(或者可能是一些额外的空格?) - readlines()如果它们在文件中,它们将保留它们。因此,您希望.rstrip() guessword,例如:

    guessword = open(category + ".txt", "r").readlines()[random.randint(0,9)].rstrip()

顺便说一句,创建这样的匿名文件对象通常不是一个好主意,因为它不会立即关闭。你最好使用with语句:

    with open(category + ".txt", "r") as f:
        guessword = f.readlines()[random.randint(0,9)].rstrip()

您可以使用

进一步优化它
    with open(category + ".txt", "r") as f:
        guessword = random.choice(f.readlines()).rstrip()