Python开发Wordle游戏时打印彩色字符出现乱码问题求助
解决Termcolor输出ANSI转义码乱码问题
我用Python开发Wordle游戏时,引入termcolor库的colored()函数实现字符彩色打印,但运行时终端出现?[32mp?[0m这类乱码;去掉colored()就正常。
我的代码
import random import sys from termcolor import colored def print_menu(): print("welcome to wordle !") print("type a 5 letter word and hit enter\n") def read_random_word(): with open('E:\\kartikey\\python\\programs\\wordle\\words.txt') as word_database: #splitline so every line in the text file gets stored as a diferent array #block and since here every line is basically a word so every word gets stored as an individual array. words=word_database.read().splitlines() return random.choice(words).lower() print_menu() play_again="" while play_again !="quit": word=read_random_word() for attempt in range(1,7): guess=input().lower() for i in range(min(len(guess),5)): if guess[i]==word[i]: #end="" is used so it doesnt go to a new line after printing the coloured letter print(colored(guess[i],'green'), end="") elif guess[i] in word: print(colored(guess[i],'yellow'), end="") else: print(guess[i] , end="") if guess==word: print((f"\nyou got the word in {attempt} try")) break elif attempt==6: print(f"sorry the wordle was {word}") play_again=input("type quit to exit otherwise click enter")
错误输出
welcome to wordle !
type a 5 letter word and hit enterpoise
?[32mp?[0m?[32mo?[0m?[32mi?[0m?[32ms?[0m?[32me?[0m
you got the word in 1 try
解决方法
乱码本质是终端不识别termcolor输出的ANSI转义码(控制颜色的特殊字符),最简便的修复方式是使用colorama库兼容Windows终端:
- 先安装colorama:
pip install colorama
- 修改代码,导入colorama并初始化:
在原代码开头添加两行:
from colorama import init init()
修改后的完整代码:
import random import sys from termcolor import colored from colorama import init init() def print_menu(): print("welcome to wordle !") print("type a 5 letter word and hit enter\n") def read_random_word(): with open('E:\\kartikey\\python\\programs\\wordle\\words.txt') as word_database: words=word_database.read().splitlines() return random.choice(words).lower() print_menu() play_again="" while play_again !="quit": word=read_random_word() for attempt in range(1,7): guess=input().lower() for i in range(min(len(guess),5)): if guess[i]==word[i]: print(colored(guess[i],'green'), end="") elif guess[i] in word: print(colored(guess[i],'yellow'), end="") else: print(guess[i] , end="") if guess==word: print((f"\nyou got the word in {attempt} try")) break elif attempt==6: print(f"sorry the wordle was {word}") play_again=input("type quit to exit otherwise click enter")
另外,如果使用的是Windows Terminal或PowerShell,也可以直接开启终端的ANSI支持,但colorama的方法兼容性更强,能适配旧版命令提示符。
内容的提问来源于stack exchange,提问作者horsei_
相关产品推荐
相关产品推荐

