python - String.maketrans 用于英语和波斯语数字

标签 python python-2.7 python-unicode

我有这样一个函数:

persian_numbers = '۱۲۳۴۵۶۷۸۹۰'
english_numbers = '1234567890'
arabic_numbers  = '١٢٣٤٥٦٧٨٩٠'

english_trans   = string.maketrans(english_numbers, persian_numbers)
arabic_trans    = string.maketrans(arabic_numbers, persian_numbers)

text.translate(english_trans)
text.translate(arabic_trans)

我希望它将所有阿拉伯语和英语数字翻译成波斯语。但是 Python 说:

english_translate = string.maketrans(english_numbers, persian_numbers)
ValueError: maketrans arguments must have same length

我尝试使用 Unicode utf-8 对字符串进行编码,但我总是遇到一些错误!有时问题是阿拉伯字符串!您知道这项工作的更好解决方案吗?

编辑:

问题似乎是 ASCII 中的 Unicode 字符长度。像“1”这样的阿拉伯数字是两个字符——我用 ord() 找到了它。长度问题从这里开始:-(

最佳答案

请参阅将所有字符串转换为 UTF8 的 unidecode 库。这在输入不同语言的数字时非常有用。

在 Python 2 中:

>>> from unidecode import unidecode
>>> a = unidecode(u"۰۱۲۳۴۵۶۷۸۹")
>>> a
'0123456789'
>>> unidecode(a)
'0123456789'

在 Python 3 中:

>>> from unidecode import unidecode
>>> a = unidecode("۰۱۲۳۴۵۶۷۸۹")
>>> a
'0123456789'
>>> unidecode(a)
'0123456789'

关于python - String.maketrans 用于英语和波斯语数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11879025/

相关文章:

python - 导入错误 : No module named pxssh

Django 存储亚马逊 S3,给出 400 个错误的请求异常

python - 打印带有 UTF-8 编码字符的字符串,例如: "\u00c5\u009b\"

python - python 中的 any() all() 函数

威尔逊分数区间的 Python 实现?

python - 从 GitLab CI 将应用程序部署到 App Engine 时权限被拒绝

python - 使用 any() 和 all() 检查列表是否包含一组值或另一个

python - Python默认字符串编码

python-3.x - 在 Python 3 中打开 tar 文件时出现 UnicodeDecodeError

python - 无法在我的 django 1.5 模板中加载 css