Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

ruby - String#encode not fixing "invalid byte sequence in UTF-8" error

I know there are multiple similar questions about this error, and I've tried many of them without luck. The problem I'm having involves the byte xA1 and is throwing

ArgumentError: invalid byte sequence in UTF-8

I've tried the following with no success:

"xA1".encode('UTF-8', :undef => :replace, :invalid => :replace,
    :replace => "").sub('', '')
"xA1".encode('UTF-8', :undef => :replace, :invalid => :replace,
    :replace => "").force_encoding('UTF-8').sub('', '')
"xA1".encode('UTF-8', :undef => :replace, :invalid => :replace,
    :replace => "").encode('UTF-8').sub('', '')

Each line throws the error for me. What am I doing wrong?

UPDATE:

The above lines fail only in IRB. However, I modified my application to encode lines of a CVS file using the same String#encode method and arguments, and I get the same error when reading the line from a file (note: it works if you perform the operations on the same string w/o using IO).

bad_line = "col1col2badxa1"

bad_line.sub('', '') # does NOT fail
puts bad_line # => col1 col2    bad?

tmp = Tempfile.new 'foo' # write the line to a file to emulate real problem
tmp.puts bad_line
tmp.close

tmp2 = Tempfile.new 'bar'

begin
  IO.foreach tmp.path do |line|
    line.encode!('UTF-8', :undef => :replace, :invalid => :replace, :replace => "")
    line.sub('', '') # fail: invalid byte sequence in UTF-8
    tmp2.puts line
  end
  tmp2.close

  # this would fail if the above error didn't halt execution
  CSV.foreach(tmp2.path) do |row|
    puts row.inspect # fail: invalid byte sequence in UTF-8
  end
ensure
  tmp.unlink
  tmp2.close
  tmp2.unlink
end
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It would seem that ruby thinks that the string encoding is already utf8, so when you do

line.encode!('UTF-8', :undef => :replace, :invalid => :replace, :replace => "")

it doesn't actually do anything because the destination encoding is the same as the current encoding (at least that's my interpretation of the code in transcode.c)

The real question here is whether your starting data is valid in some encoding that isn't utf-8 or whether this is data that is supposed to be utf-8 but has a few warts in it that you want to discard.

In the first case, the correct thing to do is tell ruby what this encoding is. You can do this when you open the file

File.open('somefile', 'r:iso-8859-1')

will open the file, interpreting its contents as iso-8859-1

You can even get ruby to transcode for you

File.open('somefile', 'r:iso-8859-1:utf-8')

will open the file as iso-8859-1, but when you read data from it the bytes will be converted to utf-8 for you.

You can also call force_encoding to tell ruby what a string's encoding is (this doesn't modify the bytes at all, it just tells ruby how to interpret them).

In the second case, where you just want to dump whatever nasty stuff has got into your utf-8, you can't just call encode! as you have because that's a no-op. In ruby 2.1 and higher, you can use String#scrub, in previous versions you can do this

line.encode!('UTF-16', :undef => :replace, :invalid => :replace, :replace => "")
line.encode!('UTF-8')

We first convert to utf-16. Since this is a different encoding, ruby will actually replace our invalid sequences. We can then convert back to utf-8. This won't lose us any extra data because utf-8 and utf-16 are just two different ways of encoding the same underlying character set.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...