[Ruby] 文字コードの判別

memo.
NKF.guess で判別するのかなー?

[markdown]
> * [module NKF](http://docs.ruby-lang.org/ja/2.1.0/class/NKF.html)
> * [かんたん10分プログラミング – 第2回 文字コードを変換するプログラム:ITpro](http://itpro.nikkeibp.co.jp/article/COLUMN/20060927/249167/)

漢字コード判別コマンドの例が載っている。

“`ruby
#!/usr/local/bin/ruby
require ‘nkf’
CODES = {
NKF::JIS => “JIS”,
NKF::EUC => “EUC”,
NKF::SJIS => “SJIS”,
NKF::UTF8 => “UTF8”,
NKF::BINARY => “BINARY”,
NKF::ASCII => “ASCII”,
NKF::UNKNOWN => “UNKNOWN”,
}
while file = ARGV.shift
str = open(file) {|io| io.gets(nil) }
printf “%-10s “, file
if str.nil?
puts “EMPTY”
else
puts CODES.fetch(NKF.guess(str))
end
end
“`

`NKF.#guess` は、漢字コードを推測して返す。

> * [module function NKF.#guess](http://docs.ruby-lang.org/ja/2.1.0/method/NKF/m/guess.html)

CSVファイルを読み込んで判別して処理して欲しい。
書いてみる。

“`ruby
require ‘optparse’
# require ‘kconv’
require ‘nkf’
require ‘csv’
require ‘pp’
#読み込んだファイルの文字コード表示用配列
CODES = {
NKF::JIS => ‘JIS’,
NKF::EUC => ‘EUC’,
NKF::SJIS => ‘SJIS’,
NKF::UTF8 => ‘UTF-8’,
NKF::UTF16 => ‘UTF-16’,
NKF::BINARY => ‘BINARY’,
NKF::ASCII => ‘ASCII’,
NKF::UNKNOWN => ‘UNKNOWN’,
}
begin
OPTS = ARGV.getopts(”)
path_to_csv = ARGV[0]
f = open(path_to_csv, ‘r’)
contents = f.read
f.close
rescue => ex
puts “Error: #{ex}”
exit
end
begin
case CODES[NKF.guess(contents)]
when ‘UTF-8’
csv = CSV.read(path_to_csv, headers: true, encoding: ‘UTF-8:UTF-8’).map(&:to_hash)
when ‘SJIS’
csv = CSV.read(path_to_csv, headers: true, encoding: ‘Shift_JIS:UTF-8’).map(&:to_hash)
else
puts ‘UTF-8 と SJIS ファイルに対応しています。’
exit
end
rescue => ex
puts “Error: #{ex}”
end
pp csv
“`

こんなでいいのかな?

## 補遺

> * [library kconv](http://docs.ruby-lang.org/ja/2.1.0/library/kconv.html)
> * [Rubyist Magazine – 標準添付ライブラリ紹介 【第 3 回】 Kconv/NKF/Iconv](http://magazine.rubyist.net/?0009-BundledLibraries)
> * [Rubyist Magazine – Ruby M17N の設計と実装](http://magazine.rubyist.net/?0025-Ruby19_m17n#l76)

「完全な文字コード判定というのは理論的には不可能」とのこと。

> * [404 Blog Not Found:ruby|perl – 文字コードのちょっと高度な判定](http://blog.livedoor.jp/dankogai/archives/50737353.html)

[brianmario/charlock_holmes](https://github.com/brianmario/charlock_holmes) という gem で文字コードの自動判別を行う。

> * [Ruby 1.9で文字コードの自動判別を行う | @masuidrive blog](http://blog.masuidrive.jp/2012/01/06/encoding-auto-detection-on-ruby-1-9/)
[/markdown]