
NChardet库为文本文件编码进行探测,其源码使用C#语言,并能自动识别txt文件中的编码。
5星
- 浏览量: 0
- 大小:None
- 文件类型:None
简介:
NChardet文本文件编码探测库的源代码,采用C#语言,提供一种用于自动识别TXT文本文件编码的方法。该库能够自动检测几乎所有主流编码格式,包括GB2312、UTF-8和ASCII等。以下是使用该库的具体步骤:`static public Encoding GetEncoding(string bookPath, ref string charsetName) { charsetName = ; // 1. Japanese // 2. Chinese // 3. Simplified Chinese // 4. Traditional Chinese // 5. Korean // 6. Dont know (默认) int lang = 2; // 使用指定的语言参数实例化Detector Detector det = new Detector(lang); // 初始化 MyCharsetDetectionObserver cdo = new MyCharsetDetectionObserver(); det.Init(cdo); // 输入字符流 Uri url = new Uri(http://cn.yahoo.com); HttpWebRequest request = HttpWebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = File.OpenRead(bookPath); byte[] buf = new byte[1024]; int len; bool done = false; bool isAscii = true; bool found = false; while ((len = stream.Read(buf, 0, buf.Length)) != 0) { // 检测是否为ASCII编码 if (isAscii) isAscii = det.isAscii(buf, len); // 如果不是ASCII编码,并且编码未确定,则继续探测 if (!isAscii && !done) done = det.DoIt(buf, len, false); } stream.Close(); stream.Dispose(); // 调用DatEnd方法,// 如果引擎认为已经探测出了正确的编码,// 则会在此时调用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) { charsetName = cdo.Charset; return GetEncodingFromEncodingName(cdo.Charset); } if (!found) { charsetName = ; string[] prob = det.getProbableCharsets(); for (int i = 0; i < prob.Length; i++) { // Console.WriteLine(Probable Charset = + prob[i]); } return Encoding.Default; } return Encoding.Default; } static public Encoding GetEncodingFromEncodingName(string charset) { if (string.IsNullOrWhiteSpace(charset)) { charset = gb2312; } return Encoding.GetEncoding(charset); }
全部评论 (0)


