1. 问题
python
File "sdk/smart_decision.py", line 146, in <module>
print(f'text: {text}')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-16: ordinal not in range(128)
2. 分析问题
你遇到的这个错误: UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-16: ordinal not in range(128) 是因为你在 Python 3 中尝试打印一个包含 非 ASCII 字符 的字符串(如中文),但当前终端/控制台不支持 UTF-8 编码,或者没有正确设置输出编码。3.
3. 解决方案
python
✅ 解决方案一:在打印前手动指定编码
你可以将
print
改为使用
.encode('utf-8', errors='ignore')
或者使用 try-except 捕获异常:
✅ 方法 1:忽略非 ASCII 字符
print(f'text: {text.encode("ascii", "ignore").decode("ascii")}')
✅ 方法 2:直接使用 UTF-8 编码处理输出
print(f'text: {text}'.encode(sys.stdout.encoding, errors='replace').decode(sys.stdout.encoding))
✅ 解决方案二:确保标准输出支持 UTF-8
你可以显式设置标准输出的编码方式为 UTF-8:
✅ 方法:在脚本开头添加以下代码
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
将其放在你的模块导入之前,比如:
# -*- coding: utf-8 -*-
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(ROOT_DIR)
from src.template_parse import TemplateParser
from src.keywords_analysis import KeywordsAnalyzer
✅ 解决方案三:修改运行环境编码设置
如果你是在 Windows 上运行脚本,可以尝试用管理员权限打开命令提示符,并运行:
chcp 65001
这会将命令行编码切换为 UTF-8。然后重新运行你的脚本。