Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中反转希伯来语字符串?_Python - Fatal编程技术网

如何在Python中反转希伯来语字符串?

如何在Python中反转希伯来语字符串?,python,Python,我试图在Python中反转希伯来语字符串: line = 'אבגד' reversed = line[::-1] print reversed 但我得到: UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 0: ordinal not in range(128) 能解释一下我做错了什么吗 编辑:答案很好,谢谢! 我还尝试使用以下命令将字符串保存到文件中: w1 = open('~/fileName',

我试图在Python中反转希伯来语字符串:

line = 'אבגד'
reversed = line[::-1]
print reversed
但我得到:

UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 0: ordinal not in range(128)
能解释一下我做错了什么吗

编辑:答案很好,谢谢! 我还尝试使用以下命令将字符串保存到文件中:

w1 = open('~/fileName', 'w')
w1.write(reverseLine)
但现在我明白了:

return codecs.charmap_encode(input,errors,encoding_table)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 1-3: character    maps to <undefined>
而不是

open('~/fileName', 'w')

您需要使用unicode字符串常量:

line = u'אבגד'
reversed = line[::-1]
print reversed

在希伯来语字符串前面添加
u
对我很有用:

In [1]: line = u'אבגד'

In [2]: reversed = line[::-1]

In [2]: print reversed
דגבא

对于第二个问题,您可以使用:

import codecs

w1 = codecs.open("~/fileName", "r", "utf-8")
w1.write(reversed)
将unicode字符串写入文件
文件名

或者,如果不使用
编解码器
,则在写入文件时,需要使用
utf-8
反向
字符串进行编码:

with open('~/fileName', 'w') as f:
    f.write(reversed.encode('utf-8'))

字符串默认被视为ascii。将u“”用于unicode

line = u'אבגד'
reversed = line[::-1]
print reversed

确保您使用的是unicode对象

line = unicode('אבגד', 'utf-8')
reversed = line[::-1]
print reversed

找到如何写入文件:

w1 = codecs.open('~/fileName', 'w', encoding='utf-8')
w1.write(reverseLine)

由于数字顺序相反等原因,翻转希伯来文背景词需要的不仅仅是反转字符串

算法要复杂得多

本页(到目前为止)中的所有答案很可能会影响你的数字和非希伯来文文本

在大多数情况下,您应该使用

from bidi.algorithm import get_display
print get_display(text)

谢谢我一直在互联网上寻找一种方法来做到这一点。希伯来文字符顺序非常复杂。看看我的答案。
from bidi.algorithm import get_display
print get_display(text)