gpt4 book ai didi

python - 了解 Python Unicode 和 Linux 终端

转载 作者:IT王子 更新时间:2023-10-29 00:23:45 26 4
gpt4 key购买 nike

我有一个 Python 脚本,它使用 UTF-8 编码编写一些字符串。在我的脚本中,我主要使用 str() 函数来转换为字符串。看起来像这样:

mystring="this is unicode string:"+japanesevalues[1] 
#japanesevalues is a list of unicode values, I am sure it is unicode
print mystring

我不使用 Python 终端,只使用标准的 Linux Red Hat x86_64 终端。我将终端设置为输出 utf8 字符。

如果我执行这个:

#python myscript.py
this is unicode string: カラダーズ ソフィー

但如果我这样做:

#python myscript.py > output

我得到了典型的错误:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 253-254: ordinal not in range(128)

这是为什么?

最佳答案

终端有一个字符集,Python 知道那个字符集是什么,所以它会自动将你的 Unicode 字符串解码为终端使用的字节编码,在你的例子中是 UTF-8。

但是当你重定向时,你不再使用终端。你现在只是在使用 Unix 管道。那个 Unix 管道没有字符集,Python 无法知道你现在想要哪种编码,所以它会回退到默认字符集。你用“Python-3.x”标记了你的问题,但你的 print 语法是 Python 2,所以我怀疑你实际上使用的是 Python 2。然后你的 sys.getdefaultencoding() 通常是 'ascii',在您的情况下肯定是这样。当然,您不能将日语字符编码为 ASCII,因此会出错。

使用 Python 2 时,最好的办法是在打印字符串之前使用 UTF-8 对其进行编码。然后重定向将起作用,生成的文件为 UTF-8。这意味着如果您的终端是其他东西,它将无法工作,但是您可以从 sys.stdout.encoding 获取终端编码并使用它(在 Python 2 下重定向时它将是 None )。

在 Python 3 中,您的代码应该按原样工作,只是您需要将 print mystring 更改为 print(mystring)

关于python - 了解 Python Unicode 和 Linux 终端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17419126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com