[英]How to Reverse Hebrew String in 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', '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>
任何想法如何解決這個問題?
編輯:找到解決方案,請參閱下面的答案。 總之我用
codecs.open('~/fileName', 'w', encoding='utf-8')
代替
open('~/fileName', 'w')
在希伯來語字符串前添加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 字符串寫入文件fileName
。
或者,在不使用codecs
,您將需要在寫入文件時使用utf-8
對reversed
字符串進行編碼:
with open('~/fileName', 'w') as f:
f.write(reversed.encode('utf-8'))
由於數字的相反順序等,您需要的不僅僅是反轉一個字符串來翻轉希伯來語 backwords。
算法要復雜得多;
此頁面中的所有答案(到目前為止)很可能會搞砸您的數字和非希伯來語文本。
對於大多數情況,您應該使用
from bidi.algorithm import get_display
print get_display(text)
您需要使用 unicode 字符串常量:
line = u'אבגד'
reversed = line[::-1]
print reversed
字符串默認被視為 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.