字符编码检测,由 ICU 提供
使用 ICU 的 Ruby 字符编码检测库
首先,您需要要求它
require 'charlock_holmes'contents = File.read('test.xml')
detection = CharlockHolmes::EncodingDetector.detect(contents)
# => {:encoding => 'UTF-8', :confidence => 100, :type => :text}
# optionally there will be a :language key as well, but
# that's mostly only returned for legacy encodings like ISO-8859-1注意: CharlockHolmes::EncodingDetector.detect 如果无法找到编码,则会返回 nil。
对于二进制内容, :type 将被设置为 :binary
虽然重复使用一次探测器实例更有效:
detector = CharlockHolmes::EncodingDetector.new
detection1 = detector.detect(File.read('test.xml'))
detection2 = detector.detect(File.read('test2.json'))
# and so on...或者,您可以直接使用 String 类中的 detect_encoding 方法
require 'charlock_holmes/string'
contents = File.read('test.xml')
detection = contents.detect_encoding注意: 此方法仅存在于 Ruby 1.9+ 中
如果您想使用此库来检测字符串的编码标志并设置该标志,可以使用 String 类中的 detect_encoding! 方法。
暂无开放 Issues,或尚未同步最近议题。