打印ascii码报错问题

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。然后重新运行你的脚本。
相关推荐
014-code2 小时前
CompletableFuture 实战模板(超时、组合、异常链处理)
java·数据库
Nicander2 小时前
多数据源下@transcation事务踩坑
java·后端
郑州光合科技余经理2 小时前
同城O2O海外版二次开发实战:从支付网关到配送算法
开发语言·前端·后端·算法·架构·uni-app·php
Ujimatsu2 小时前
虚拟机安装Ubuntu 26.04.x及其常用软件(2026.4)
linux·运维·ubuntu
それども2 小时前
DELETE 和 TRUNCATE TABLE区别
java·数据库·mysql
冰暮流星2 小时前
javascript事件案例-全选框案例
服务器·前端·javascript
sjsjsbbsbsn3 小时前
大模型核心知识总结
java·人工智能·后端
Csvn3 小时前
前端性能优化实战指南
前端
Moment3 小时前
2026 年,AI 全栈时代到了,前端简历别再只写前端技术了 🫠🫠🫠
前端·后端·面试