Termcolor 返回奇怪的字符串

Termcolor returning strange string of characters

我正在尝试构建我自己的 Wordle 版本,但我被困在这里。这部分代码的目的是在匹配秘密词的位置和字母时将适当的字符着色为绿色,在匹配字母但不匹配位置时将其着色为黄色。不包含在密字中的字符不着色。

from termcolor import colored
secret = "widow"

def color(word):
    if word[0] == secret[0]:
        word = word.replace(word[0], colored(word[0], 'green'))
    if word[0] == secret[1] or secret[2] or secret[3] or secret[4]:
        word = word.replace(word[0], colored(word[0], 'yellow'))
    if word[1] == secret[1]:
        word = word.replace(word[1], colored(word[1], 'green'))
    if word[1] == secret[0] or secret[2] or secret[3] or secret[4]:
        word = word.replace(word[1], colored(word[1], 'yellow'))
    if word[2] == secret[2]:
        word = word.replace(word[2], colored(word[2], 'green'))
    if word[2] == secret[1] or secret[0] or secret[3] or secret[4]:
        word = word.replace(word[2], colored(word[2], 'yellow'))
    if word[3] == secret[3]:
        word = word.replace(word[3], colored(word[3], 'green'))
    if word[3] == secret[1] or secret[2] or secret[0] or secret[4]:
        word = word.replace(word[3], colored(word[3], 'yellow'))
    if word[4] == secret[4]:
        word = word.replace(word[4], colored(word[4], 'green'))
    if word[4] == secret[1] or secret[2] or secret[3] or secret[0]:
        word = word.replace(word[4], colored(word[4], 'yellow'))
    return word

print(color("woiky"))

在这个例子中,我希望“woiky”打印出绿色的“w”(因为 woiky 和 ​​widow 都以“w”开头)、黄色的“i”和黄色的“o”(因为“寡妇”同时包含“i”和“o”,但不在这些位置),而是打印: [33m[[0m33m[33m[[0m[33m[[0m0m33m[33m[[0m33m[33m[[0m[33m[[0m0m[33m[[0m33m[33m[[0m[33m[[0m0m0m33m[33m[[0m33m [33m[[0m[33m[[0m0m33m[33m[[0m33m[33m[[0m[33m[[0m0m[33m[[0m33m[33m[[0m[33m[[0m0m0m0m[33m[[0m33m[33m[[0m [33m[[0m0m33m[33m[[0m33m[33m[[0m[33m[[0m0m[33m[[0m33m[33m[[0m[33m[[0m0m0m32mw[33m[[0m33m[33m[[0m[33m[[0m0m33m [33m[[0m33m[33m[[0m[33m[[0m0m[33m[[0m33m[33m[[0m[33m[[0m0m0m33m[33m[[0m33m[33m[[0m[33m[[0m0m33m[33m[[0m33m [33m[[0m[33m[[0m0m[33m[[0m33m[33m[[0m[33m[[0m0m0m0m[33m[[0m33m[33m[[0m[33m[[0m0m33m[33m[[0m33m[33m[[0m [33m[[0m0m[33m[[0m33m[33m[[0m[33m[[0m0m0m0moiky

而且所有的“[”字符都是黄色的。

这应该以更智能的方式做你想做的事。我不想下载termcolor,所以我提供了一个替代。

#from termcolor import colored
secret = "widow"

def colored(a,b):
    return( f"<{b}>{a}</{b}>" )

def color(word):
    build = []
    for i,letter in enumerate(word):
        if letter == secret[i]:
            build.append( colored(letter, 'green'))
        elif letter in secret:
            build.append( colored(letter, 'yellow'))
        else:
            build.append( letter )
    return ''.join(build)

print(color("woiky"))