Web Spider提取编码方法总结(二)

4,通过字节流分析检测编码
  UTF8判断部分的C#代码:

  int utf8_probability(byte[] rawtext)
  {
   int score = 0;
   int i, rawtextlen = 0;
   int goodbytes = 0, asciibytes = 0;

   // Maybe also use UTF8 Byte Order Mark:  EF BB BF

   // Check to see if characters fit into acceptable ranges
   rawtextlen = rawtext.Length;
   for (i = 0; i < rawtextlen; i++)
   {
    if ((rawtext[i] & (byte)0x7F) == rawtext[i])
    {  // One byte
     asciibytes++;
     // Ignore ASCII, can throw off count
    }
    else
    {
     int m_rawInt0 = Convert.ToInt16(rawtext[i]);
     int m_rawInt1 = Convert.ToInt16(rawtext[i+1]);
     int m_rawInt2 = Convert.ToInt16(rawtext[i+2]);

     if (256-64 <= m_rawInt0 && m_rawInt0 <= 256-33 && // Two bytes
      i+1 < rawtextlen &&
      256-128 <= m_rawInt1 && m_rawInt1 <= 256-65)
     {
      goodbytes += 2;
      i++;
     }
     else if (256-32 <= m_rawInt0 && m_rawInt0 <= 256-17 && // Three bytes
      i+2 < rawtextlen &&
      256-128 <= m_rawInt1 && m_rawInt1 <= 256-65 &&
      256-128 <= m_rawInt2 && m_rawInt2 <= 256-65)
     {
      goodbytes += 3;
      i+=2;
     }
    }
   }

   if (asciibytes == rawtextlen) { return 0; }

   score = (int)(100 * ((float)goodbytes/(float)(rawtextlen-asciibytes)));

   // If not above 98, reduce to zero to prevent coincidental matches
   // Allows for some (few) bad formed sequences
   if (score > 98)
   {
    return score;
   }
   else if (score > 95 && goodbytes > 30)
   {
    return score;
   }
   else
   {
    return 0;
   }
  } 

参考资料:
字符检测程序(上) 检测GB2312、BIG5...    
http://dev.csdn.net/Develop/article/10/article/10/10961.shtm
Hello Unicode ——JAVA的中文处理学习笔记
http://www.chedong.com/tech/hello_unicode.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值