Skip to main content
 首页 » 编程设计

python之如何使用python将阿拉伯字符映射到英文字符串

2025年05月04日55mfrbuaa

我正在尝试读取一个包含阿拉伯字符(如“ù”)的文件并将其映射到英文字符串“AYN”。我想在 Python 3.4 中创建所有 28 个阿拉伯字母到英文字符串的映射。我仍然是 Python 的初学者,不知道如何开始。具有阿拉伯字符的文件以 UTF8 格式编码。

请您参考如下方法:

使用unicodedata;

(注意:这是 Python 3。在 Python 2 中使用 u'ù' 代替)

In [1]: import unicodedata 
 
In [2]: unicodedata.name('a') 
Out[2]: 'LATIN SMALL LETTER A' 
 
In [6]: unicodedata.name('ع') 
Out[6]: 'ARABIC LETTER AIN' 
 
In [7]: unicodedata.name('ع').split()[-1] 
Out[7]: 'AIN' 

最后一行适用于简单字母,但不适用于所有阿拉伯符号。例如。带下面三个点的阿拉伯文字母FEH。

所以你可以使用;

In [26]: unicodedata.name('ڥ').lower().split()[2] 
Out[26]: 'feh' 

或

In [28]: unicodedata.name('ڥ').lower()[14:] 
Out[28]: 'feh with three dots below' 

为了识别字符,使用类似这样的东西(Python 3);

c = 'ع' 
id = unicodedata.name(c).lower() 
if 'arabic letter' in id: 
    print("{}: {}".format(c, id[14:].lower())) 

这会产生;

ع: ain 

我正在过滤字符串 'arabic letter' 因为 arabic unicode block还有很多其他符号。

一个完整的字典可以用:

arabicdict = {} 
for n in range(0x600, 0x700): 
    c = chr(n) 
    try: 
        id =  unicodedata.name(c).lower() 
        if 'arabic letter' in id: 
            arabicdict[c] = id[14:] 
    except ValueError: 
        pass