From: ytakagi Date: 2013-01-09T13:35:49+09:00 Subject: [ruby-list:49126] pure ruby のコードで日本語の文字コードを推測したい。 ここは jruby の話題も ok なんでしょうか? jruby 1.7.2 (ruby 1.9.3p327) を使用しています。 jruby の nkf ライブラリは不完全とされていますので、 日本語の文字コードの推測を、ぜひ pure ruby のコードで 行いたいのです。 いまのところ、 http://0xcc.net/blog/archives/000005.html のページなどを参考にして、 下記のようなコードを試しにこのあいだ書いてみました。 手元ではまあまあいいようにも感じていますが、 こんな感じでいいのかどうかも、いまいち確信がもてません。 pure ruby のコードでの、日本語の文字コード推測 の決定版を確定していただけませんか? メーリングリストの趣旨に外れていないようでしたら、 どうかよろしくお願いします。 require 'iconv' class Iconv Preference = ["iso-2022-jp", 'euc-jp', 'utf-8', 'shift_jis', 'windows-31j'] def self.encname_guess(str) return "us-ascii" if /\A[\r\n\t\x20-\x7e]*\Z/n.match(str) rescue{} Preference.each {|name| begin return name if Iconv.conv("UTF-8", name, str) rescue Iconv::IllegalSequence end } return 'unable to convert to UTF-8' #raise 'unable to convert to UTF-8' end end =begin # example # encname_guess.rb より上記スクリプトを読み込み。 require 'encname_guess' result_encname = Iconv.encname_guess(target_str) # result_encnameは、 # "us-ascii", "iso-2022-jp", 'euc-jp', 'utf-8', 'shift_jis', 'windows-31j' # のいずれか。 =end