Python 3 print()函数,带有波斯语/阿拉伯语字符

2024-09-28 03:14:36 发布

您现在位置:Python中文网/ 问答频道 /正文

为了更好地理解,我简化了代码。 问题是:

案例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的结果:

?????? ??? ??????

它运行时没有错误。

截图:

enter image description here

有关如何将65001设置为默认字符集的详细信息,请签出this


Tags: 代码text字符x86案例utfencodealso
3条回答

输出基本上取决于运行代码的平台和终端。让我们为运行2.x或3.x的不同windows终端检查以下代码片段:

# -*- coding: utf-8 -*-
import sys

def case1(text):
    print(text)

def case2(text):
    print(text.encode("utf-8"))

def case3(text):
    sys.stdout.buffer.write(text.encode("utf-8"))

if __name__ == "__main__":
    text = "چرا کار نمیکنی؟"

    for case in [case1, case2, case3]:
        try:
            print("Running {0}".format(case.__name__))
            case(text)
        except Exception as e:
            print(e)

        print('-'*80)

结果

Python 2.x

Sublime Text 3 3122

    Running case1
    'charmap' codec can't encode characters in position 0-2: character maps to <undefined>
    --------------------------------------------------------------------------------
    Running case2
    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'
    --------------------------------------------------------------------------------
    Running case3
    چرا کار نمیکنی؟--------------------------------------------------------------------------------

ConEmu v151205型

    Running case1
    ┌åÏ▒Ϻ ┌®ÏºÏ▒ ┘å┘à█î┌®┘å█îσ
    --------------------------------------------------------------------------------
    Running case2
    'ascii' codec can't decode byte 0xda in position 0: ordinal not in range(128)
    --------------------------------------------------------------------------------
    Running case3
    'file' object has no attribute 'buffer'
    --------------------------------------------------------------------------------

Windows命令提示符

    Running case1
    ┌åÏ▒Ϻ ┌®ÏºÏ▒ ┘å┘à█î┌®┘å█îσ
    --------------------------------------------------------------------------------

    Running case2
    'ascii' codec can't decode byte 0xda in position 0: ordinal not in range(128)
    --------------------------------------------------------------------------------

    Running case3
    'file' object has no attribute 'buffer'
    --------------------------------------------------------------------------------

Python 3.x

Sublime Text 3 3122

    Running case1
    'charmap' codec can't encode characters in position 0-2: character maps to <undefined>
    --------------------------------------------------------------------------------
    Running case2
    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'
    --------------------------------------------------------------------------------
    Running case3
    چرا کار نمیکنی؟--------------------------------------------------------------------------------

ConEmu v151205型

    Running case1
    'charmap' codec can't encode characters in position 0-2: character maps to <undefined>
    --------------------------------------------------------------------------------
    Running case2
    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'
    --------------------------------------------------------------------------------
    Running case3
    ┌åÏ▒Ϻ ┌®ÏºÏ▒ ┘å┘à█î┌®┘å█îσ--------------------------------------------------------------------------------

Windows命令提示符

    Running case1
    'charmap' codec can't encode characters in position 0-2: character maps to <unde
    fined>
    --------------------------------------------------------------------------------

    Running case2
    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'
    --------------------------------------------------------------------------------

    Running case3
    ┌åÏ▒Ϻ ┌®ÏºÏ▒ ┘å┘à█î┌®┘å█îσ----------------------------------------------------
    ----------------------------

如你所见,使用sublime text3终端(case3)工作正常。其他终端不支持波斯语。这里的要点是,这取决于您使用的终端和平台。

解决方案(特定于ConEmu)

像ConEmu这样的现代终端允许您使用UTF8编码作为explained here,所以,让我们尝试一下:

chcp 65001 & cmd

然后对2.x&3.x再次运行脚本:

Python2.x

Running case1
��را کار نمیکنی؟[Errno 0] Error
--------------------------------------------------------------------------------
Running case2
'ascii' codec can't decode byte 0xda in position 0: ordinal not in range(128)
--------------------------------------------------------------------------------
Running case3
'file' object has no attribute 'buffer'
--------------------------------------------------------------------------------

Python3.x

Running case1
چرا کار نمیکنی؟
--------------------------------------------------------------------------------
Running case2
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'
--------------------------------------------------------------------------------
Running case3
چرا کار نمیکنی؟--------------------------------------------------------------------------------

如您所见,现在python3 case1(print)的输出成功了。所以。。。寓言的寓意。。。了解更多关于您的工具以及如何为您的用例正确配置它们的信息;-)

我无法再现这个问题。这是我的脚本p.py

text = "چرا کار نمیکنی؟"
print(text)

以及python3 p.py的结果:

چرا کار نمیکنی؟

你确定你在使用python 3吗?使用python2 p.py

SyntaxError: Non-ASCII character '\xda' in file p.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

您的代码是正确的,因为它在我的计算机上同时使用Python2和3(我在OSX上):

~$ python -c 'print "تست"'
تست
~$ python3 -c 'print("تست")'
تست

问题是您的终端无法输出unicode字符。您可以通过将输出重定向到类似python3 my_file.py > test.txt的文件并使用编辑器打开该文件来验证它。

如果您使用的是Windows,那么可以使用像Console2ConEmu这样的终端,它比Windows prompt更好地呈现unicode。

由于Windows的代码页/编码错误,这些终端也可能遇到错误。有一个小python包可以修复它们(正确设置它们):

1-安装thispip install win-unicode-console

2-将它放在python文件的顶部:

try:
    # Fix UTF8 output issues on Windows console.
    # Does nothing if package is not installed
    from win_unicode_console import enable
    enable()
except ImportError:
    pass

如果重定向到文件时出错,可以通过设置io编码进行修复:

在Windows命令行上:

SET PYTHONIOENCODING=utf-8

在Linux/OS X终端上:

export PYTHONIOENCODING=utf-8

某些点

  • 在python 3中不需要使用u"aaa"语法。默认情况下,字符串文本为unicode。
  • 在python 3中,文件的默认编码是UTF8,因此不需要编码声明注释(例如# -*- coding: utf-8 -*-)。

相关问题 更多 >

    热门问题