检查n是否在数组中

2024-04-26 17:57:15 发布

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

我想在python3中创建一个程序,允许用户输入单词的字母数量,以及一些字母。你知道吗

例如:

>> Input how many letters there are in the word
> 5

>> Put _ if no letter is shown, and letter that is shown down
> _ell_

>> Possible finds: Hello, Mello
>> Update the search
> Hell_

>> Final find: Hello
>> Restart?:
> Yes

我真的不知道如何用恰当的语言来解释这一点,但你们是开发人员,所以我相信你们理解这一点。你知道吗

您可以让用户输入单词中字母的数量。 然后让user input _作为空白字母和正确的字母显示(st_ing >> string) 然后它会从字典数组或文本文件(数组的意思是words = ["word1", "word2", word3"]等)中找到一些与搜索匹配的单词 如果没有超过1个查找,则可以键入以缩小搜索范围 一旦只有1个find,它将提示重新启动,然后yes=restart。你知道吗

我是python新手,所以这对我来说可能是最复杂的,这就是为什么我要问你!你知道吗

我在问这会有多复杂,如果可能的话,我会怎么做。我已经开始了,这是我现在所拥有的一切:(记住我刚刚开始)

two_word = ["hi", "ai", "no", "id"]
three_word = ["run", "buy", "tie", "bit", "fat"]
four_word = ["help", "file", "edit", "code", "user"]
five_word = ["couch", "cough", "coach", "stars", "spoon", "sunny", "maths"]

letter_count = input("How much letters are there?: ")
letter_count = int(letter_count)

if letter_count == 2:
    wordlist = two_word

elif letter_count == 3:
    wordlist = three_word

elif letter_count == 4:
    wordlist = four_word

elif letter_count == 5:
    wordlist = five_word

else:
    print("Improper entry.")


guess = input("The word right now: ")

blanks = guess.count("_")
#I don't know how to check for certain letters and how to convert _ to the word in the wordlist
#That is why I'm asking

Tags: theto用户input数量iscount字母
1条回答
网友
1楼 · 发布于 2024-04-26 17:57:15

如果我开发这个,我会:

  • 把所有单词放在一个set
  • 跳过第一个问题(你可以通过第二个问题的长度来确定单词的长度)
  • 为您向用户提出的每个问题设置一个while循环,以便它在无效输入时重复相同的问题。你知道吗

要检查单词,可以compile a regular expression并将所有_替换为.

regex = re.compile(guess.replace('_', '.') + '$')

现在是您一直在等待的部分,检查集合中的项是否匹配:

match = [m.group(0) for word in wordlist for m in [regex.match(word)] if m]
print(' '.join(match) or "No matches")

The list comprehension above basically iterates through every word in the list (which can be prefiltered by length if you prefer), then checks it to see if it matches the regular expression created earlier. If it's a match, m will be a Match Object that you can get the first group of which will be the word you are looking for all packaged together as a list of words that match.

The last line prints all the matches separated by a space, or "No matches" if there isn't any matches.

这段代码未经测试,我对python3的熟悉程度不如对python2的熟悉。祝你好运!你知道吗

相关问题 更多 >