VSCode终端无法正常输出阿拉伯字符的技术求助
解决VSCode终端阿拉伯语显示与编码问题
一、修复'charmap'编码错误
Windows终端默认编码不是UTF-8,导致阿拉伯语字符无法编码输出,两种解决方式:
- 代码层面强制UTF-8输出:在代码开头添加以下代码,直接修改标准输出的编码:
import sys sys.stdout.reconfigure(encoding='utf-8') - VSCode终端设置调整:打开设置(快捷键
Ctrl+,),搜索terminal.integrated.encoding,将值改为utf-8;同时建议把terminal.integrated.defaultProfile.windows设置为PowerShell或Git Bash,避免使用默认CMD(CMD默认编码不支持UTF-8)。
二、解决阿拉伯语显示为????乱码
乱码核心原因是终端字体不支持阿拉伯语字符,需更换支持阿拉伯语的字体:
打开VSCode设置,搜索terminal.integrated.fontFamily,设置值为支持阿拉伯语的字体列表,例如:
"Segoe UI Arabic", "Noto Naskh Arabic", "Arial Unicode MS"
三、修正阿拉伯语从左到右显示的问题
单独运行代码时方向错误,需从两方面排查:
- 终端双向文本支持:确保使用的终端(如VSCode内置终端、Windows Terminal)支持双向文本渲染,新版VSCode终端已默认支持,若为旧版本建议升级。
- 依赖库版本:旧版
arabic_reshaper或python-bidi可能存在兼容性问题,执行以下命令更新到最新版:pip install --upgrade arabic-reshaper python-bidi
四、优化后的完整代码
整合上述修复后的代码如下:
import speech_recognition as sr import arabic_reshaper import sys from bidi.algorithm import get_display # 强制标准输出使用UTF-8编码 sys.stdout.reconfigure(encoding='utf-8') def command(): r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") r.pause_threshold = 0.6 audio = r.listen(source) try: # 测试阿拉伯语显示 test_reshaped = arabic_reshaper.reshape("مرحبا") print(get_display(test_reshaped)) ask = r.recognize_google(audio, language='ar-SA') reshaped_ask = arabic_reshaper.reshape(ask) bidi_text = get_display(reshaped_ask) print(bidi_text) except Exception as e: print("Error:", str(e)) print("Say that again...") return "" return ask command()
内容的提问来源于stack exchange,提问作者sami
相关产品推荐
相关产品推荐

