为了更好地理解,我简化了代码。 问题是:
案例1:
# -*- coding: utf-8 -*-
text = "چرا کار نمیکنی؟" # also using u"...." results the same
print(text)
输出:
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-2: character maps to <undefined>
案例2:
text = "چرا کار نمیکنی؟".encode("utf-8")
print(text)
没有输出。
case3:
import sys
text = "چرا کار نمیکنی؟".encode("utf-8")
sys.stdout.buffer.write(text)
输出:
چرا کار نمیکنی؟
我知道case 3可以工作,但是我想使用其他函数,比如print()、write(str())、。。。。
我还阅读了python 3关于Unicodehere的文档。
还阅读了stackoverflow中的几十个问题解答。
here是一篇很长的文章,解释了python 2.X的问题和答案
简单的问题是:
如何使用python print()函数打印波斯语或阿拉伯语等非ASCII字符?
更新1: 正如许多人所说,问题与我测试的终端有关:
案例4:
text = "چرا کار نمیکنی؟" .encode("utf-8")# also using u"...." results the same
print(text)
终端:
python persian_encoding.py > test.txt
test.txt文件:
b'\xda\x86\xd8\xb1\xd8\xa7 \xda\xa9\xd8\xa7\xd8\xb1 \xd9\x86\xd9\x85\xdb\x8c\xda\xa9\xd9\x86\xdb\x8c\xd8\x9f'
非常重要的更新:
在处理这个问题一段时间后,我终于找到了另一个解决方法,让cmd.exe完成这项工作(不需要像ConEmu或…)这样的第三方软件:
先解释一下:
我们的主要问题与Python无关。这是Windows中命令提示符字符集的问题(有关完整解释,请查看Arman的答案) 所以。。。如果将Windows命令提示符的字符集更改为UTF-8而不是默认的ascii,则命令提示符将能够与UTF-8字符(如波斯语或阿拉伯语)交互此解决方案不能保证字符的良好表示(因为它们将像小正方形一样打印出来),但如果希望使用UTF-8字符的python文件I/O。
步骤:
从命令行启动python之前,请键入:
chcp 65001
现在像往常一样运行python代码。
python testcode.py
案例1的结果:
?????? ??? ??????
它运行时没有错误。
截图:
有关如何将65001设置为默认字符集的详细信息,请签出this。
输出基本上取决于运行代码的平台和终端。让我们为运行2.x或3.x的不同windows终端检查以下代码片段:
结果
Python 2.x
ConEmu v151205型
Windows命令提示符
Python 3.x
ConEmu v151205型
Windows命令提示符
如你所见,使用sublime text3终端(case3)工作正常。其他终端不支持波斯语。这里的要点是,这取决于您使用的终端和平台。
解决方案(特定于ConEmu)
像ConEmu这样的现代终端允许您使用UTF8编码作为explained here,所以,让我们尝试一下:
然后对2.x&3.x再次运行脚本:
Python2.x
Python3.x
如您所见,现在python3 case1(print)的输出成功了。所以。。。寓言的寓意。。。了解更多关于您的工具以及如何为您的用例正确配置它们的信息;-)
我无法再现这个问题。这是我的脚本
p.py
:以及
python3 p.py
的结果:你确定你在使用python 3吗?使用
python2 p.py
:您的代码是正确的,因为它在我的计算机上同时使用Python2和3(我在OSX上):
问题是您的终端无法输出unicode字符。您可以通过将输出重定向到类似
python3 my_file.py > test.txt
的文件并使用编辑器打开该文件来验证它。如果您使用的是Windows,那么可以使用像Console2或ConEmu这样的终端,它比Windows prompt更好地呈现unicode。
由于Windows的代码页/编码错误,这些终端也可能遇到错误。有一个小python包可以修复它们(正确设置它们):
1-安装this
pip install win-unicode-console
2-将它放在python文件的顶部:
如果重定向到文件时出错,可以通过设置io编码进行修复:
在Windows命令行上:
在Linux/OS X终端上:
某些点
u"aaa"
语法。默认情况下,字符串文本为unicode。# -*- coding: utf-8 -*-
)。相关问题 更多 >
编程相关推荐