Python 中的阿拉伯语单词

Arabic words in Python

我在 Python 中打印阿拉伯语文本时遇到问题,我编写了一个将英语字符转换为阿拉伯语的代码(聊天语言或 F运行co Arabic),然后创建不同结果的组合以根据用户输入获得建议。

def transliterate(francosentence, verbose=False):
    francowords = francosentence.split()
    arabicconvertedwords = []
    for i in francowords:
        rankeddata=[]
        rankeddata=transliterate_word(i)
        arabicconvertedwords.append(rankeddata)
        for index in range(len(rankeddata)):
            print rankeddata[index]

    ran=list(itertools.product(*arabicconvertedwords))
    for I in range(len(ran)):
        print ran[I]

第一次打印 (print 运行keddata[index]) 给出了阿拉伯语单词,但是在执行组合过程后第二次打印 (print 运行[I]) 给出了类似的东西: (u'\u0627\u0646\u0647', u'\u0631\u0627\u064a\u062d', u'\u0627\u0644\u062c\u0627\u0645\u0639\u0647')

如何打印阿拉伯语单词?

您的第二个循环运行了 unicodetuple 秒(product 一次产生一个产品作为 tuple),而不是单个 [=15] =] 值。

虽然 print 使用打印对象的 str 形式,但 tuplestr 形式使用包含对象的 repr,它不传播 "str-iness"(从技术上讲,tuple 完全缺少 __str__,因此它回落到 __repr__)。

如果您想查看阿拉伯语,则需要单独打印元素或将它们连接起来以便打印字符串,而不是 tuple。例如,您可以更改:

print ran[I]

类似于:

print u', '.join(ran[I])

将转换为单个逗号分隔的 unicode 值,print 将按预期格式(str 形式),而不是使用 repr 形式对非 ASCII 值进行转义。

旁注:作为风格(和内存使用)的要点,直接使用迭代器协议,不要 list 化所有内容然后使用 C 风格的索引循环。如果输入很大(输出的总大小是每个输入长度的乘积),以下代码必须在内存中存储大量内容:

ran=list(itertools.product(*arabicconvertedwords))
for I in range(len(ran)):
    print u', '.join(ran[I])

它可以轻松地按需一次只生成一个项目,从而更快地生成结果而没有内存开销:

# Don't listify...
ran = itertools.product(*arabicconvertedwords)
for r in ran:  # Iterate items directly, no need for list or indexing
    print u', '.join(r)