如何在Ruby中将字符串转换为UTF8

cie*_*bor 50 ruby encoding dump file utf-8

我正在写一个使用Hpricot的爬虫.它从某个网页下载一个字符串列表,然后我尝试将其写入该文件.编码有问题:

"\xC3" from ASCII-8BIT to UTF-8
Run Code Online (Sandbox Code Playgroud)

我有在网页上呈现并以这种方式打印的项目:

Développement
Run Code Online (Sandbox Code Playgroud)

str.encoding回报UTF-8,所以force_encoding('UTF-8')没有帮助.我怎么能把它转换成可读的UTF-8?

Ste*_*fan 57

您的字符串似乎编码错误:

"Développement".encode("iso-8859-1").force_encoding("utf-8")
#=> "Développement"
Run Code Online (Sandbox Code Playgroud)

  • 抱歉,这并不是为了解决问题。您应该通过在将字符串读入应用程序时设置/检测正确的编码来解决问题。 (2认同)
  • 还可以选择使用“Encoding::UTF_8”,而不是为““utf-8””字符串文字(或任何其他编码字符串)使用更多内存。 (2认同)

knu*_*nut 47

似乎你的字符串认为它是UTF-8,但实际上,它是其他东西,可能是ISO-8859-1.

首先定义(强制)正确的编码,然后将其转换为UTF-8.

在你的例子中:

puts "Développement".encode('iso-8859-1').encode('utf-8')
Run Code Online (Sandbox Code Playgroud)

另一种选择是:

puts "\xC3".force_encoding('iso-8859-1').encode('utf-8') #-> Ã
Run Code Online (Sandbox Code Playgroud)

如果Ã没有意义,那么尝试另一种编码.


小智 5

ruby 1.9:UTF-8中的无效字节序列 ”描述了另一种使用较少代码的好的方法:

file_contents.encode!('UTF-16', 'UTF-8')
Run Code Online (Sandbox Code Playgroud)