【问题标题】:Iconv and Kconv on Ruby (1.9.2)Ruby 上的 Iconv 和 Kconv (1.9.2)
【发布时间】:2011-06-26 18:58:09
【问题描述】:

我知道 Iconv 用于转换字符串的编码。 根据我的理解,Kconv 是出于同样的目的(我错了吗?)。

我的问题是:它们之间有什么区别,我应该使用什么进行编码转换。

顺便说一句,Iconv 将在 1.9.3 版本中被弃用。

【问题讨论】:

  • Kconv 好像只针对汉字?

标签: ruby character-encoding iconv


【解决方案1】:

正如https://stackoverflow.com/users/23649/jtbandes 所说,它看起来Kconv 类似于Iconv,但专门用于汉字(“现代日语书写系统中与平假名一起使用的表意汉字”http://en.wikipedia.org/wiki/Kanji)。除非您正在研究专门的日语,否则我猜您不需要Kconv

如果您使用的是 Ruby 1.9,则大多数时候您可以使用内置编码支持来代替 Iconv。在我读到这篇文章之前,我尝试了几个小时来理解我在做什么:

http://www.joelonsoftware.com/articles/Unicode.html

然后你就可以开始使用类似的东西了

String#encode           # Ruby 1.9
String#encode!          # Ruby 1.9
String#force_encoding   # Ruby 1.9

充满信心。如果您有更复杂的需求,请阅读http://blog.grayproductions.net/categories/character_encodings

已更新感谢 cmets 中的 JohnZ

Iconv 在 Ruby 1.9 中仍然有用,因为它可以音译字符(这是String#encode 等人无法做到的)。下面是一个如何扩展String 的示例,该函数使用音译为 UTF-8 的函数:

require 'iconv'
class ::String
  # Return a new String that has been transliterated into UTF-8
  # Should work in Ruby 1.8 and Ruby 1.9 thanks to http://po-ru.com/diary/fixing-invalid-utf-8-in-ruby-revisited/
  def as_utf8(from_encoding = 'UTF-8')
    ::Iconv.conv('UTF-8//TRANSLIT', from_encoding, self + ' ')[0..-2]
  end
end

"foo".as_utf8 #=> "foo"
"foo".as_utf8('ISO-8859-1') #=> "foo"

谢谢约翰!

【讨论】:

  • String#encode 和朋友的问题是,如果您的字符串不是String#valid_encoding?,他们将无济于事;即使您将#force_encoding 您的字符串,您也可能会得到一个非#valid_encoding? 字符串。 Iconv 具有音译无效字符的能力。是的,您可以将它们删除/替换为#encode,但它与Iconv 的音译表不同。
  • 关于您的更新:您的方法 as_utf8 仅在您要“修复”不是 String#valid_Encoding? 的 utf-8 字符串时才有用。这是因为您将第二个参数(即from 编码)设置为静态'UTF-8'
猜你喜欢
  • 1970-01-01
  • 2011-10-11
  • 1970-01-01
  • 2011-09-17
  • 2012-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多