2011-02-17 24 views
3

我有這樣的遺留代碼片段,其中(顯然)雙UTF-8編碼的文本到正常的UTF-8解碼回譯雙UTF-8解碼器代碼:如何在Python到Lua

# Run with python3! 
import codecs 
import sys 
s=codecs.open('doubleutf8.dat', 'r', 'utf-8').read() 
sys.stdout.write(
       s 
       .encode('raw_unicode_escape') 
       .decode('utf-8') 
     ) 

我需要將它翻譯成Lua,並模仿所有可能的解碼副作用(如果有的話)。

限制:我可以使用任何可用的Lua模塊進行UTF-8處理,但最好是穩定的Lua模塊,支持LuaRocks。我不會使用Lupa或其他Lua-Python橋接解決方案,我也不會使用os.execute()來調用Python。

回答

3

您可以使用lua-iconv,Lua綁定到iconv library。有了它,您可以儘可能多地在字符編碼之間進行轉換。

它也可在LuaRocks

編輯:使用this answer我已經能夠在數據使用下面的Lua代碼正確解碼:

require 'iconv' 
-- convert from utf8 to latin1 
local decoder = iconv.new('latin1', 'utf8') 
local data = io.open('doubleutf8.dat'):read('*a') 
-- decodedData is encoded in utf8 
local decodedData = decoder:iconv(data) 
-- if your terminal understands utf8, prints "нижний новгород" 
-- if not, you can further convert it from utf8 to any encoding, like KOI8-R 
print(decodedData) 
+0

嗯,謝謝,但問題的關鍵是,我有點迷茫Python的UTF轉換內容(例如,什麼是`raw_unicode_escape`),並且希望看到一段實際的Lua代碼。對不起,這裏很懶。 – 2011-02-17 19:47:05