如何将Python中的双UTF-8解码器代码翻译为Lua

3 投票
1 回答
1829 浏览
提问于 2025-04-16 12:01

我有一段老旧的代码,它的作用是把双重编码的UTF-8文本解码回正常的UTF-8格式:

# 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,但最好是稳定的,并且支持LuaRocks。我不会使用Lupa或其他Lua和Python之间的桥接解决方案,也不会调用os.execute()来运行Python。

1 个回答

3

你可以使用 lua-iconv,这是一个可以让Lua语言使用的工具,跟 iconv库 相关联。通过这个工具,你可以随意在不同的字符编码之间进行转换。

这个工具也可以在 LuaRocks 上找到。

编辑:根据 这个回答,我已经能够使用以下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)

撰写回答