替换列表中的字符,即使它出现多次

时间:2017-06-01 11:42:05

标签: python list replace

我正在为Python做臭名昭着的Hangman游戏。这是我的代码:

import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
    inFile = open(WORDLIST_FILENAME, 'r', 0)
    line = inFile.readline()
    wordlist = string.split(line)
    return wordlist
def choose_word(wordlist):
    return random.choice(wordlist)
wordlist = load_words()
word=list(choose_word(wordlist))          #I read that it's preferable to
print "Welcome to the game, Hangman!"     #use lists as string are more
print "I am thinking of a word that is", len(word), "letters long." #tricky
def check(word):                           #because they are immutable and 
    guesses=20                            #some problems might arise
    let="abcdefghijklmnopqrstuvwxyz"
    altword=list(len(word)*"-")
    while "-" in altword and guesses>0:
        print "You have", guesses, "guesses left."
        print "Available letters: ", let
        letter=raw_input("Please guess a letter: ")
        newlet=let.replace(letter, "")
        let=newlet
        if letter in word:
            index=word.index(letter)          #here is the problem when a
            altword[index]=letter             #letter appears more than once
            print "Good guess: ", ''.join(map(str, altword))
        else:
            guesses=guesses-1
            print "Oops! That letter is not in my word: ", ''.join(map(str, altword))
    if guesses<=0:
        print "Sorry, you've been hanged! The word is: ", ''.join(map(str, word))
    else:
        print "Congratulations, you won!"
check(word)

如果字母出现多次,如何替换altword 中的"-"?我试图以其他方式说出来,但问题是所述字母可能或可能在任何给定的单词中多次出现,我需要先检查一下。

2 个答案:

答案 0 :(得分:0)

只需你可以这样查看

'apple'.count('p')

这会让你在苹果中出现p 或者您可以使用相同的方法来检测句子中的单词

"apple are red and bananas are yellow and oranges are orange".count("and")

答案 1 :(得分:0)

你不必计算出现的次数,对于游戏逻辑,如果猜测的字母是正确的(在单词中)或不正确的(不在单词中),它是非常重要的。

要替换所有匹配项,您可以使用简单for - 循环enumerate

if letter in word:
    for idx, char in enumerate(word):  # go through the word (remembering the index)
        if char == letter:             # check if it is a match
            altword[idx] = letter      # replace the character at idx in "altword" with "letter"
    print "Good guess: ", ''.join(map(str, altword))
else:
    guesses -= 1
    print "Oops! That letter is not in my word: ", ''.join(map(str, altword))