【问题标题】:Inconsistent IO character reading when converting encoding转换编码时 IO 字符读取不一致
【发布时间】:2013-06-07 21:50:06
【问题描述】:

在 Ruby 1.9.3-429 中,我试图解析具有各种编码的纯文本文件,这些编码最终将转换为 UTF-8 字符串。非 ascii 字符适用于编码为 UTF-8 的文件,但非 UTF-8 文件会出现问题。

简化示例:

File.open(file) do |io|
  io.set_encoding("#{charset.upcase}:#{Encoding::UTF_8}")
  line, char = "", nil

  until io.eof? || char == ?\n || char == ?\r
    char = io.readchar
    puts "Character #{char} has #{char.each_codepoint.count} codepoints"
    puts "SLICE FAIL" unless char == char.slice(0,1)

    line << char
  end
  line
end

这两个文件都只是一个经过适当编码的字符串áÁð。我已通过$ file -i &lt;file_name&gt;检查文件是否已正确编码

使用 UTF-8 文件,我返回:

Character á has 1 codepoints
Character Á has 1 codepoints
Character ð has 1 codepoints

使用 ISO-8859-1 文件:

Character á has 2 codepoints
SLICE FAIL
Character Á has 2 codepoints
SLICE FAIL
Character ð has 2 codepoints
SLICE FAIL

我对此的解释是 readchar 正在返回一个错误转换的编码,这导致切片返回不正确。

这种行为正确吗?还是我错误地指定了文件外部编码?我宁愿不重写这个过程,所以我希望我在某个地方犯了错误。我以这种方式解析文件是有原因的,但我认为这些与我的问题无关。在File.open 中指定内部和外部编码作为选项产生了相同的结果。

【问题讨论】:

    标签: character-encoding ruby-1.9


    【解决方案1】:

    这种行为是一个错误。详情请见http://bugs.ruby-lang.org/issues/8516

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2011-09-17
      • 2012-02-27
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      相关资源
      最近更新 更多