这个游戏现在我已经解决了直到最后。但是这里还有一个问题是如何替换字符串中的重复单词?请帮我!谢谢。例如:我的自定义文件里面有单词:“apple”,当用破折号隐藏单词时:“-----”但是当我用破折号替换字符串时我只能用1 p代替破折号:“ap-le”如何用2p代替破折号:“apple”。我以前的帖子为这个程序:How do i detect the repeat input in my hangman game (Python)!。这是我要替换的代码:
def getGuessedWord():
pos = word.index(guessword.lower())
print(pos)
global words
words = words[:pos]+ guessword.lower() +words[pos+1:]
print(words)
return words
答案 0 :(得分:0)
我对过滤猜测字母的整体问题的解决方案是以下一组功能:
guessed_letters = set()
def guess(letter):
global guessed_letters
guessed_letters.add(letter)
def filter_letter(letter):
if letter in guessed_letters:
return letter
else:
return '-'
def filtered(words):
for word in words:
output = ''
for letter in word:
output += filter_letter(letter)
yield output
或更紧凑:
guessed_letters = set()
def guess(letter):
global guessed_letters
guessed_letters.add(letter)
def filter_letter(letter):
return letter if letter in guessed_letters else '-'
def filtered(words):
return [''.join(map(filter_letter, word)) for word in words]
这样:
>>> words = "bubbly water".split()
>>> guess('a')
>>> ' '.join(filtered(words))
'------ -a---'
>>> guess('b')
>>> ' '.join(filtered(words))
'b-bb-- -a---