python中的字符串编码

获取字符串的编码类型:

encodingdate = chardet.detect(str)

chardet用于实现字符串的编码类型检测

chardet的下载地址:https://pypi.python.org/pypi/chardet/

查看获取到的编码类型:

print encodingdate['encoding']

将字符串转为unicode:

ustr = unicode(str, encodingdate['encoding'])

将unicode转为字符串:

ustr.encode('utf-8', 'ignore')

 需要注意的是encode方法,str类型也有这个接口,

但是这个接口的作用是将unicode编码成指定编码的字符串,在str上是无效的。

一个相对复杂的应用:

字符串转unicode在搜索引擎abelkhan 爬虫部分的应用

            for name,value in attrs:
                if name == 'content':
                    try:
                        if isinstance(value, str):
                            encodingdate = chardet.detect(value)
                            if encodingdate['encoding']:
                                value = unicode(value, encodingdate['encoding'])

                        if self.style == 'keywords':
                            keywords = doclex.simplesplit(value)
                            if isinstance(keywords, list):
                                for key in keywords:
                                    self.urlinfo['keys']['1'].append(key)

                        elif self.style == 'profile':
                            self.urlinfo['profile'].append(value)

                            keys1 = doclex.lex(value)
                            for key in keys1:
                                self.urlinfo['keys']['2'].append(key)

                            keys1 = doclex.vaguesplit(value)
                            for key in keys1:
                                self.urlinfo['keys']['3'].append(key)

                            tlen = 16
                            if len(value) < 16:
                                tlen = len(value)
                            self.urlinfo['title'].append(value[0:tlen])

                    except:
                        import traceback
                        traceback.print_exc()

开源的搜索引擎,欢迎大家支持!

项目地址:http://www.abelkhan.com/

向我们提出意见:http://www.abelkhan.com/guestbook/

对项目进行捐助:http://www.abelkhan.com/collection/

代码托管地址如下:https://github.com/qianqians/websearch欢迎大家参与

原文地址:https://www.cnblogs.com/qianqians/p/5321301.html