Universalchardet
提供:やる気向上作戦
目次 |
universalchardet / juniversalchardet
Mozillaのエンコーディング判別ライブラリであるuniversalchardetを切り出して、Cライブラリ化してみた。さらにJavaにもポーティングしてみた。エンコーディング判別なのにcharacter set detectorとはこれいかに。
C版はLinux/Windowsに対応。Linuxでのインストールは make && make install で。autoconfなどという高尚なものは使っておりません。
文字コードの変換はこちら EncodingConversion
Related Works
- jchardet (Java,旧バージョンのchardet)
- juniversalchardet(Java,universalchardetのJavaポート)
- Universal Encoding Detector (Python)
- Universal Encoding Detector in Ruby (Ruby,上のポーティング)
判別可能なエンコーディング
- Chinese
- ISO-2022-CN
- BIG5
- X-EUC-TW
- GB18030
- HZ-GB-2312
- Cyrillic
- ISO-8859-5
- KOI8-R
- windows-1251
- x-mac-cyrillic
- IBM866
- IBM855
- Greek
- ISO-8859-7
- windows-1253
- Hebrew
- ISO-8859-8
- windows-1255
- Japanese
- ISO-2022-JP
- Shift_JIS
- EUC-JP
- Korean
- ISO-2022-KR
- EUC-KR
- Unicode
- UTF-8
- UTF-16BE / UTF-16LE
- UTF-32BE / UTF-32LE / X-ISO-10646-UCS-4-3412 / X-ISO-10646-UCS-4-2143
- Others
- ISO-8859-1
使い方
詳しくはuniversalchardet.hを参照。
#include "universalchardet.h"
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
char encoding[32];
chardet_t det = NULL;
const char* str = "あいうえお";
// 判別器を構築
chardet_create(&det);
// データを処理
chardet_handle_data(det, str, (unsigned int)strlen(str));
chardet_data_end(det);
// 判別結果を取得
chardet_get_charset(det, encoding, sizeof(encoding));
printf("Encoding = %s\n", encoding);
// 破壊
chardet_destroy(det);
return 0;
}
juniversalchardetなら、以下のようになる。
import org.mozilla.universalchardet.UniversalDetector;
public class TestDetector
{
public static void main(String[] args)
{
byte[] buf = new byte[4096];
java.io.FileInputStream fis = new java.io.FileInputStream("test.txt");
// 判別器を構築
UniversalDetector detector = new UniversalDetector(null);
// 判別器にデータを与える
int nread;
while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
detector.handleData(buf, 0, nread);
}
// データの終わりを判別器に通知する
detector.dataEnd();
// 判別結果を取得する
String encoding = detector.getDetectedCharset();
if (encoding != null) {
System.out.println("Detected encoding = " + encoding);
} else {
System.out.println("No encoding detected.");
}
}
}
ライセンス
MPL1.1/GPL2.0/LGPL2.1 のいずれかを選択