什么是nchardet
nchardet是mozilla自動(dòng)字符編碼識(shí)別程序庫(kù)chardet的.net實(shí)現(xiàn),它移植自jchardet,chardet的java版實(shí)現(xiàn),可實(shí)現(xiàn)對(duì)給定字符流的編碼探測(cè)。
nchardet是如何工作的
nchardet通過逐個(gè)比較輸入字符來猜測(cè)編碼;由于是猜測(cè),所以可能會(huì)有不能完全識(shí)別的情況;如果輸入字符不能確定正確的編碼,那么nchardet會(huì)給出一組可能的編碼值。
如何使用nchardet
要使用nchardet來探測(cè)編碼,需要進(jìn)行如下步驟。
1、使用制定的語(yǔ)言線索來構(gòu)造detector類的實(shí)例對(duì)象。
2、用實(shí)現(xiàn)了icharsetdetectionobserver接口的對(duì)象作為參數(shù)來調(diào)用detector類的init方法。
3、傳入要探測(cè)的字符流進(jìn)行編碼探測(cè)。
4、調(diào)用detector類的dataend方法。
5、得到結(jié)果或可能的結(jié)果集。
語(yǔ)言線索是一個(gè)整數(shù),可用的語(yǔ)言線索有如下幾個(gè):
1. japanese
2. chinese
3. simplified chinese
4. traditional chinese
5. korean
6. dont know (默認(rèn))
icharsetdetectionobserver接口只有一個(gè)notify方法,當(dāng)nchardet引擎認(rèn)為自己已經(jīng)探測(cè)出正確的編碼時(shí),它就會(huì)調(diào)用這個(gè)notify方法,用戶程序可以從這個(gè)nodify方法中得到通知(重寫icharsetdetectionobserver接口的notify實(shí)現(xiàn))。
代碼實(shí)例:
//實(shí)現(xiàn)icharsetdetectionobserver接口
public class mycharsetdetectionobserver :
nchardet.icharsetdetectionobserver
{
public string charset = null;
public void notify(string charset)
{
charset = charset;
}
}
int lang = 2 ;//
//用指定的語(yǔ)參數(shù)實(shí)例化detector
detector det = new detector(lang) ;
//初始化
mycharsetdetectionobserver cdo = new mycharsetdetectionobserver();
det.init(cdo);
//輸入字符流
uri url = new uri(“http://cn.yahoo.com”);
httpwebrequest request =
httpwebrequest)webrequest.create(url);
httpwebresponse response =
(httpwebresponse)request.getresponse();
stream stream = response.getresponsestream();
byte[] buf = new byte[1024] ;
int len;
bool done = false ;
bool isascii = true ;
while( (len=stream.read(buf,0,buf.length)) != 0) {
// 探測(cè)是否為ascii編碼
if (isascii)
isascii = det.isascii(buf,len);
// 如果不是ascii編碼,并且編碼未確定,則繼續(xù)探測(cè)
if (!isascii && !done)
done = det.doit(buf,len, false);
}
stream.close();
stream.dispose();
//調(diào)用datend方法,
//如果引擎認(rèn)為已經(jīng)探測(cè)出了正確的編碼,
//則會(huì)在此時(shí)調(diào)用icharsetdetectionobserver的notify方法
det.dataend();
if (isascii) {
console.writeline("charset = ascii");
found = true ;
}
else if (cdo.charset != null)
{
console.writeline("charset = {0}",cdo.charset);
found = true;
}
if (!found) {
string[] prob = det.getprobablecharsets() ;
for(int i=0; i<prob.length; i++) {
console.writeline("probable charset = " + prob[i]);
}
}
console.readline();
新聞熱點(diǎn)
疑難解答
圖片精選