根据已检查的数量检查字符串中字符实例的数量

  • 本文关键字:字符 实例 字符串 python string
  • 更新时间 :
  • 英文 :


我正在用Python重新创建Wordle,但遇到了一个问题。即使字母太多,它也会突出显示黄色。例如,如果单词是gas,并且您输入了一个单词(如gss(,即使单词中只有1,它也会高亮显示两个字母s。这是我的代码:

import random
import time
import sys
import os
if os.name == 'nt':
from ctypes import windll
k = windll.kernel32
k.SetConsoleMode(k.GetStdHandle(-11), 7)
keys = {'a': 'NSr', 'b': 'rlK', 'c': 'yDD', 'd': 'YBr', 'e': 'XBB', 'f': 'LLo', 'g': 'gZn', 'h': 'LTd', 'i': 'hKn', 'j': 'fWj', 'k': 'dgu', 'l': 'nFN', 'm': 'nNy',
'n': 'QKD', 'o': 'cJJ', 'p': 'MEA', 'q': 'WTJ', 'r': 'nnM', 's': 'Tru', 't': 'xcE', 'u': 'Msx', 'v': 'Cef', 'w': 'Hkf', 'x': 'obn', 'y': 'myp', 'z': 'PUE'}
keyr = {v: k for k, v in keys.items()}
def encrypt(text):
if len(text) > 1:
string = ""
for char in text:
if char in keys:
string += keys[char] + ","
else:
return "Only letters are allowed"
break
return string
else:
return "Text must have something in it"
def decrypt(text):
text = text[:-1].split(",")
if len(text) > 1:
string = ""
for char in text:
if char in keyr:
string += keyr[char]
else:
return "Only letters are allowed"
break
return string
else:
return "Text must have something in it"
print("Welcome to Wordle!")
print("Random or Custom Word?")
ch = input("Type 'r' or 'c' ")
if ch not in ("r", "c"):
while ch not in ("r", "c"):
ch = input("Type 'r' or 'c' ")
green = "u001b[32m"
yellow = "u001b[33m"
reset = "u001b[0m"
if ch == "r":
letters = "abcdefghijklmnopqrstuvwxyz"
ln = {}
for char in letters:
ln[char] = 0
words = open("words.txt", "r")
wordl = []
for item in words.readlines():
wordl.append(item.strip())
word = wordl[random.randint(0, 5756)]
print(f'Your word is 5 letters. Start guessing!')
num = 1
correct = False
while num < 6:
guess = input(f'Guess {str(num)}: ').lower()
sys.stdout.write("33[F")
invalid = False
for char in guess:
if char not in keys:
print(" " * 250)
sys.stdout.write("33[F")
print("Must be only letters!")
invalid = True
if len(guess) > 5:
print(" " * 250)
sys.stdout.write("33[F")
print("Word is too long.")
elif len(guess) < 5:
print(" " * 250)
sys.stdout.write("33[F")
print("Word is too short.")
elif guess not in wordl:
print(" " * 250)
sys.stdout.write("33[F")
print("Invalid word.")
elif invalid:
pass
else:
if guess == word:
print("Your word is correct!")
correct = True
break
chn = 0
colored = ""
for char in guess:
if char in word:
if char == word[chn]:
colored += f'{green}{char}{reset}'
else:
colored += f'{yellow}{char}{reset}'
else:
colored += char
chn += 1
print(f'Guess {str(num)}: ' + colored)
num += 1
if correct == False:
print(f'You lose! The word was {word}. Better luck next time!')
else:
print("Congratulations! You win!")
time.sleep(999)

我尝试的解决方案是创建一个包含每个字母及其出现次数的字典,以重置您输入的每个单词,如下所示:

letters_n = {}
letters = "abcdefghijklmnopqrstuvwxyz"
for char in letters:
letters_n[char] = 0

然后,当它检查一个字母时,我加上数字,并将其与单词中的字符数进行核对:

for char in guess:
if char in word:
if char == word[chn]:
colored += f'{green}{char}{reset}'
else:
if letters_n[char] >= word.count(char):
colored += char
else:
colored += f'{yellow}{char}{reset}'
letters_n[char] += 1
else:
colored += char

它仍然突出显示了单词中没有的黄色字母。我该怎么解决这个问题?(抱歉代码样本太长(

检查完这些字母后,您需要消除它们。

这使用了2个循环,这样所有的绿色字母都将成为先例,然后黄色和白色字母将被考虑。

else:
if guess == word:
print("Your word is correct!")
correct = True
break
arr = list(word) # this is a copy of your actual word
ans = [None for _ in range(len(arr))] # this is your colored string output
for i, char in enumerate(guess): # check only for green letters first
if char == arr[i]:
ans[i] = f"{green}{char}{reset}" # print green
arr[i] = None # remove the letter so it can't be checked again
for i, char in enumerate(guess): # check for yellow and white letters
if char in arr and ans[i] is None:
ans[i] = f"{yellow}{char}{reset}" # print yellow
elif ans[i] is None:
ans[i] = char # print white
arr[i] = None # remove the letter so it can't be checked again

print(f'Guess {str(num)}: ' + "".join(ans)) # print the guess with the correct colouring
num += 1 # increment number of guesses

最新更新