python取余什么意思_python中取余

首先取响应头里的编码,如果是几种中文编码之一,则认为中文网页,如果不是中文编码, 也不是几种unicode方案之一, 则不是中文.否则再在标签里找 charset ,如果有并且为几种中文编码之一, 则是中文如果不是中文编码, 也不是几种unicode方案之一, 则不是中文.否则对body的内容(如果考虑性能问题,可以不对整个body,只对前N个字节)用正则洗标签过滤所有ASCII码字符, 剩余部分按字取内码,如果考虑性能问题其实取第一个字符就可以了,如果性能不重要,可以多采样几个(防止一个页面有中文日文等各种文字混合)判断采到的字符的内码是否位于中文unicode区域.如果性能非常不重要, 只是要代码简单, 那么做法可以: 正则 1 这样可以取到第一个不是ASCII的字符, 判断这个字符是否是中文字符就可以了参考代码:#! /usr/bin/env python

# -*- encoding: utf-8 -*-

import requests

import cld2

class Detector(object):

zh_cn_encodes = ('gbk', 'gb2312', 'gb18030')

def __init__(self, context):

self.context = context

def is_zh_cn_encoding(self, ctype):

ctype = ctype.lower()

for ec in self.zh_cn_encodes:

if ec in ctype:

return True

return False

def detect(self):

assert type(self.context) == type(u''), 'detect unicode string only'

ret = cld2.detect(self.context.encode('utf-8'))

return ret[2][0][1] == 'zh'

def url_detect(self):

r = requests.get(self.context)

assert r.status_code == 200, 'http code 200 is required'

ctype = r.encoding

if ctype and self.is_zh_cn_encoding(ctype):

return True

else:

self.context = r.text

return self.detect()

if __name__ == '__main__':

print Detector(u'短中文有bug').detect()

print Detector(u'网页文件一般没问题').detect()

print Detector(u'これは日本で').detect()

url = 'http://segmentfault.com/q/1010000000432652'

print Detector(url).url_detect()

url = 'https://code.google.com/p/chromium-compact-language-detector/source/browse/README'

print Detector(url).url_detect()

x00-xff ↩

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值