如何在Ruby中将字符串转换为UTF8 [英] How to convert a string to UTF8 in Ruby

查看:441
本文介绍了如何在Ruby中将字符串转换为UTF8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个使用Hpricot的爬虫。它从一些网页下载一个字符串列表,然后尝试将其写入该文件。编码时出错:

 ASCII \\ 8BIT到UTF-8

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

 Développement 

str.encoding 返回 UTF-8 ,所以 force_encoding('UTF-8')没有帮助如何将其转换为可读的UTF-8?

解决方案

您的字符串似乎已经被编码错误的方式: p>

 Développement.encode(iso-8859-1)。force_encoding(utf-8)
#=> Développement


I'm writing a crawler which uses Hpricot. It downloads a list of strings from some webpage, then I try to write it to the file. Something is wrong with the encoding:

"\xC3" from ASCII-8BIT to UTF-8

I have items which are rendered on a webpage and printed this way:

Développement

the str.encoding returns UTF-8, so force_encoding('UTF-8') doesn't help. How may I convert this to readable UTF-8?

解决方案

Your string seems to have been encoded the wrong way round:

"Développement".encode("iso-8859-1").force_encoding("utf-8")
#=> "Développement"

这篇关于如何在Ruby中将字符串转换为UTF8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆