Python Dictionary帮助,检查Dictionary obj中是否有字符

2024-10-03 02:46:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典对象

secret = {"word" : secretWord}

secretWord是包含单个单词的字符串的参数。我还有一个字符串,为secretWord中的每个字符生成一个星号(*)。在我的代码中,我从用户那里得到了一个字母。你知道吗

我希望完成的是在dictionary对象secretWord中进行检查,如果是这样,则在相关的地方用输入替换任何星号。但是,我不知道如何将此保存为新参数,然后在新参数上使用下一个输入。你知道吗

抱歉,如果我的问题/问题不清楚,因为我正在努力如何表达它。你知道吗

我想发生什么:

例如,secretWord可以是'PRECEDENCE'

>>>
WORD : **********
Guess a letter: e
**E*E*E**E
Guess a letter: p
P*E*E*E**E
etc

发生了什么:

>>>
WORD : **********
Guess a letter: e
**E*E*E**E
Guess a letter: p
P*********
etc

我的当前代码:

import random
import sys

def diction(secretWord, lives):

    global guess
    global secret

    secret = {"word" : secretWord, "lives" : lives}
    guess = len(secret["word"]) * "*"
    print (secret["word"])
    print ("WORD: ", guess) 

fileName = input("Please insert file name: ")

def wordGuessed(guess, secret):
    if guess == secret["word"]:
        print ("word is guessed")
    if guess != secret["word"]:
        print ("word is not guessed")

def livesLeft(inpu):
    if inpu not in secret["word"]:
        secret["lives"] = secret["lives"] - 1
        print("Lives left: ", secret["lives"])
    if inpu in secret["word"]:
        print("Correct guess")
        print(secret["lives"])


def guessCheck(inpu):
    for char in secret["word"].lstrip():
        if char == inpu:
            print (char, end= "")
        elif char != secret["word"]:
            print ("*", end="")


try:
    f = open(fileName)
    content = f.readlines()
except IOError as e :
    f = None
    print("Failed to open", fileName, "- program aborted")
    sys.exit()

Run = True

while Run == True:
    levelIn = input("Enter difficulty (easy, intermediate or hard): ").lower()
    if levelIn == ("easy"):
        lives = 10

    elif levelIn == ("intermediate"):
        lives = 8

    elif levelIn == ("hard"):
        lives = 5

    else:
        print("Please input a valid difficulty.")
        break



    secretWord = (random.choice(content))
    secretWord = secretWord.replace("\n", "")


    diction(secretWord, lives)
    wordGuessed(guess, secret)

    while secret["lives"] > 0:
        inpu = input("Guess a letter: ").upper()
        livesLeft(inpu)
        guessCheck(inpu)
    if secret["lives"] == 0:
        print ("You have no lives left – you have been hung!")
        print ("The word was,", secret["word"])

Tags: input参数secretifdefwordprintguess
1条回答
网友
1楼 · 发布于 2024-10-03 02:46:18

您需要跟踪到目前为止所做的猜测,并使用这些猜测来显示单词。使用一个集合跟踪玩家已经猜到的内容:

guessed = set()

这样你就可以:

if inpu in guessed:
    print('You already tried that letter!')
else:
   guessed.add(inpu)

每当用户猜测时。你知道吗

然后,您可以使用该集合来显示迄今为止显示的单词:

for char in secret["word"].lstrip():
    if char in guessed:
        print (char, end="")
    else:
        print ("*", end="")

相关问题 更多 >