我有一个在 Windows 上运行的 Ruby 程序,它使用 Open3 调用一个 shell 命令(已知输出 UTF-16):
attrs={}
attrs[:stdout], attrs[:stderr], status = Open3.capture3(command)
unless attrs[:stderr].nil?
begin
attrs[:stderr].force_encoding(Encoding::UTF_16LE).encode!(Encoding::UTF_8)
rescue => e
attrs[:stderr] = attrs[:stderr].bytes.to_json.encode!(Encoding::UTF_8)
end
end
如果对 UTF_16LE 的 force_encoding 不起作用,并引发异常,我只需保存字节,将其编码为 JSON 字符串并将其编码为 UTF_8。
嗯....抛出异常,我在救援子句中捕获了输出字节数组。它看起来像这样:
[10,84,104,105,115,32,97,112,112,108,105,99,97,116,105,111,110,32,104,97,115,32,114,101,113,117,101,115,116,101,100,32,116,104,101,32,82,117,110,116,105,109,101,32,116,111,32,116,101,114,109,105,110,97,116,101,32,105,116,32,105,110,32,97,110,32,117,110,117,115,117,97,108,32,119,97,121,46,10,80,108,101,97,115,101,32,99,111,110,116,97,99,116,32,116,104,101,32,97,112,112,108,105,99,97,116,105,111,110,39,115,32,115,117,112,112,111,114,116,32,116,101,97,109,32,102,111,114,32,109,111,114,101,32,105,110,102,111,114,109,97,116,105,111,110,46,10]
如何将其转换回某种格式的文本。例如如果我这样做:
irb> "dog".bytes
=> [100, 111, 103]
irb> "कुत्रा".bytes
=> [224, 164, 149, 224, 165, 129, 224, 164, 164, 224, 165, 141, 224, 164, 176, 224, 164, 190]
有没有办法以编程方式将 [100, 111, 103] 转换为“dog”或 [224, 164, 149, 224, 165, 129, 224, 164, 164, 224, 165, 141, 224, 164 , 176, 224, 164, 190] 回到“कुत्रा”?有没有办法弄清楚我的字节输出数组的含义?
------------------------更新-------------------- ------
我研究了一下,但花了一段时间,因为“解码”不是一回事。但是,我对保存在变量 message 中的数组执行了以下操作:
message.map{|c| c.chr}.join("")
=> "\nThis application has requested the Runtime to terminate it in an unusual way.\nPlease contact the application's support team for more information.\n"
所以我的问题解决了,因为错误消息不是 UTF-16LE。
但是,当我这样做时,我得到了如下结果:
irb> "कुत्रा".bytes.map{|c| c.chr}.join("")
=> "\xE0\xA4\x95\xE0\xA5\x81\xE0\xA4\xA4\xE0\xA5\x8D\xE0\xA4\xB0\xE0\xA4\xBE"
如何将这个看起来很奇怪的字符串或字节序列转换成更有意义的“कुत्रा”?
最佳答案
回答关于字节的第一个问题,看看数组中的 Pack 方法:docs .
[100, 111, 103].pack('U*') # Returns 'dog'.
“U*”格式尝试在字节数组中匹配尽可能多的 UTF8 字符。
如果您在错误消息中使用该方法,您会得到:
"\nThis application has requested the Runtime to terminate it in an unusual way.\nPlease contact the application's support team for more information.\n"
------------------------更新-------------------- ------
刚刚注意到您弄清楚了第一部分并添加了一个新问题。
How do I convert this strange looking string or byte sequence into the more meaningful "कुत्रा" ?
当你执行 "string".bytes.map{|c| c.chr}.join("")
新字符串上的字节是一样的,只是编码丢失了。这可以在这里看到:
s = "dog"
s.encoding #=> #<Encoding:UTF-8>
s = "dog".bytes.map{|c| c.chr}.join("") #=> "dog"
s.encoding #=> #<Encoding:US-ASCII>
这对于像“dog”这样的字符串具有预期的效果,因为 UTF-8 向后兼容 ASCII-8BIT,这意味着仅使用 ASCII-8BIT 字符的字符串将在 UTF-8 中工作。但是对于在 UTF-8 中使用超过 1 个字节的字符,例如“€”,它们在 ASCII 中无法识别。因此,要回答您的问题,您需要做的是强制对字符串进行适当的编码,如下所示:
"कुत्रा".bytes.map{|c| c.chr}.join("").force_encoding('UTF-8') #=> "कुत्रा"
希望对你有帮助
关于我认为 Ruby UTF-16 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32959217/