为什么我在读取文本文件时出现"UTF-8中的无效字节序列"错误?

Nat*_*Nat 1 ruby string encoding

我正在编写一个Ruby脚本来处理一个大文本文件,并继续得到奇怪的编码错误.情况如下:

input_data = File.new(in_path, 'r').read
p input_data.encoding.name   #   UTF-8 
break_char = "\r".encode("UTF-8")
p break_char # "\r"
p break_char.encoding.name # "UTF-8" 
input_data.split(",".encode("UTF-8"))
p Encoding.compatible?(input_data, break_char) # # Encoding:UTF-8>
Run Code Online (Sandbox Code Playgroud)

这会产生错误 :in 'split': invalid byte sequence in UTF-8 (ArgumentError)

我阅读http://blog.grayproductions.net/articles/ruby_19s_string并查看其他解决方案显然是同样的问题,但是当我相信我正在控制编码时仍然无法解决为什么会发生这种情况.

我在OSX上使用ruby 1.9.2

Mla*_*vić 8

显然你的输入文件不是UTF-8(或至少,不完全).如果您不关心非ascii字符,您可以简单地假设您的文件是ascii-8bit编码.顺便说一下,你的separator(break_char)不会引起问题,因为逗号在UTF-8中的编码方式与ASCII中相同.

fname = 'test.in'

# create example file and fill it with invalid UTF-8 sequence
File.open(fname, 'w') do |f|
  f.write "\xc3\x28"
end

# then try to read and parse it
s = File.open(fname) do |f| # file opened as UTF-8
#s = File.open(fname, 'r:ascii-8bit') do |f| # file opened as ascii-8bit
  f.read
end
p s.split ','
Run Code Online (Sandbox Code Playgroud)