添加反斜杠来修复 ruby 字符串中的字符编码
我确信这很容易,但我被所有这些反斜杠打结了。
我有一些数据是从网站上(礼貌地)抓取的。有时我会想到这样一句话:
u00a362 000? you must be joking
这当然应该是“2000 英镑?”你一定是在开玩笑吧”。在 irb 中进行了一个简短的测试,破译了它。
ruby-1.9.2-p180 :001 > string = "u00a3"
=> "u00a3"
ruby-1.9.2-p180 :002 > string = "\u00a3"
=> "£"
当然:加一个反斜杠就会被解码。我在 的帮助下创建了以下内容这个问题:
puts str.gsub('u00', '\\u00')
导致输出\u00a3
。这一切都很好,但我希望它是字符串本身中的 £。仅仅 puts
还不够。
这样做 gsub('u00a3', '£')
没有什么好处,因为毫无疑问我会丢失其他字符。
感谢您的帮助。
I'm sure this is very easy but I'm getting tied in a knot with all these backslashes.
I have some data that I'm scraping (politely) from a website. Occasionally a sentence comes to me looking something like this:
u00a362 000? you must be joking
Which should of course be '£2 000? you must be joking'. A short test in irb deciphered it.
ruby-1.9.2-p180 :001 > string = "u00a3"
=> "u00a3"
ruby-1.9.2-p180 :002 > string = "\u00a3"
=> "£"
Of course: add a backslash and it will be decoded. I created the following with the help of this question:
puts str.gsub('u00', '\\u00')
which resulted in \u00a3
being output. This is all well and good, but I want it to be £ in the string itself. just puts
ing it isn't enough.
It's no good doing gsub('u00a3', '£')
as there will doubtless be other characters I'm missing.
thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用 Iconv 库来转换传入的字符串。您也可以看看 stringex gem。它有“走另一条路”的方法,但它可能会提供您正在寻找的映射。也就是说,如果编码不好,就不可能得到正确的结果。
Try the Iconv library for converting the incoming string. You might also take a look at the stringex gem. It has methods to "go the other way" but it may provide the mappings you're looking for. That said if you've got bad encoding it can be impossible to get it right.
警告,下面的内容并不漂亮。
所以这里的想法是找到
u00xx
值并将它们转换为十六进制。从那里,我们可以使用pack
输出正确的 unicode 字符的方法。它也可以用可怕的单行来嘎吱嘎吱!
可能有更好的解决方案(我希望!),但这个可行。
Warning, the following is not really pretty.
So the idea here is to find
u00xx
values and convert them to hex. From there, we can use thepack
method to output the right unicode characters.It can also be crunched in an horrible one-liner!
There might be a better solution (I hope!) but this one works.