17

我正在使用 Python 2.7,我尝试打印这样的阿拉伯语字符串

print "ذهب الطالب الى المدرسة"

它给出以下输出:

ط°ظ‡ط¨ ط§ظ„ط·ط§ظ„ط¨ ط§ظ„ظ‰ ط§ظ„ظ…ط¯ط±ط³ط©

目的是正确打印文本,而不是如何打印每一行。那么,如何以原始形式正确打印文本文件的字符串或内容?喜欢:

ذهب الطالب الى المدرسة
4

8 回答 8

16

通过这个模块,您可以纠正您的文本形状的方向。只需安装点子并使用它。

# install: pip install --upgrade arabic-reshaper
import arabic_reshaper

# install: pip install python-bidi
from bidi.algorithm import get_display

text = "ذهب الطالب الى المدرسة"
reshaped_text = arabic_reshaper.reshape(text)    # correct its shape
bidi_text = get_display(reshaped_text)           # correct its direction
于 2019-04-20T12:42:11.797 回答
6

以下代码有效:

import arabic_reshaper

text_to_be_reshaped =  'اللغة العربية رائعة'

reshaped_text = arabic_reshaper.reshape(text_to_be_reshaped)

rev_text = reshaped_text[::-1]  # slice backwards 

print(rev_text)
于 2019-09-15T06:35:27.617 回答
3

尝试这个:

print u"ذهب الطالب الى المدرسة"

输出:

ذهب الطالب الى المدرسة

演示:https ://repl.it/EuHM/0

默认的 Python2.7 字符串使用 utf-8 字符集。并且阿拉伯语不包含在 utf-8 中。因此,如果您为其添加前缀uthen 它将将该字符串视为 unicode 字符串。

于 2016-12-20T13:15:58.977 回答
1
import sys
text = "اطبع هذا النص".encode("utf-8")

或者

text = "اطبع هذا النص".encode()

然后

sys.stdout.buffer.write(text)

输出

"اطبع هذا النص"
于 2020-09-11T12:08:10.937 回答
0

您有两个问题...首先您使用的是非阿拉伯字体或非 Unicode 文本...其次您需要这样的函数来混合纯阿拉伯字母并为您提供混合阿拉伯字母:

def mixARABIC(string2):
    import unicodedata
    string2 = string2.decode('utf8')
    new_string = ''
    for letter in string2:
        if ord(letter) < 256: unicode_letter = '\\u00'+hex(ord(letter)).replace('0x','')
        elif ord(letter) < 4096: unicode_letter = '\\u0'+hex(ord(letter)).replace('0x','')
        else: unicode_letter = '\\u'+unicodedata.decomposition(letter).split(' ')[1]
        new_string += unicode_letter
    new_string = new_string.replace('\u06CC','\u0649')
    new_string = new_string.decode('unicode_escape')
    new_string = new_string.encode('utf-8')
    return new_string
于 2021-06-22T03:44:14.980 回答
0

在蟒蛇 2.7

在文件的最顶部,您可以声明:

# -*- coding: utf-8 -*-
print "ذهب الطالب الى المدرسة"

更新:

如果你可以运行这个:

# -*- coding: utf-8 -*-
s = "ذهب الطالب الى المدرسة"
with open("file.txt", "w", encoding="utf-8") as myfile:
    myfile.write(s)

并且生成的文件“file.txt”包含正确的字符串,那么无论您在不是python本身中显示的内容都是问题,我想您可以尝试在其他内容中显示它,甚至可能是PyQt。

于 2016-12-20T13:19:37.387 回答
0

您需要在代码之前添加一些行

import sys
reload(sys)
sys.setdefaultencoding('utf-8')  
print "ذهب الطالب الى المدرسة"
于 2016-12-20T13:47:30.537 回答
0

您可以u像这样为您的字符串添加前缀

print u"ذهب الطالب الى المدرسة"

或使自己与 python3 兼容并将其放在文件的顶部

from __future__ import unicode_literals

Python27 strings(或者bytestrings它们在 Python3 中所知道的)不处理 unicode 字符。theuimport语句都使您的字符串 unicode 兼容。

于 2016-12-20T14:00:08.150 回答