python中的字符串编码
2016-03-25 21:47
471 查看
获取字符串的编码类型:
chardet用于实现字符串的编码类型检测
chardet的下载地址:https://pypi.python.org/pypi/chardet/
查看获取到的编码类型:
将字符串转为unicode:
将unicode转为字符串:
需要注意的是encode方法,str类型也有这个接口,
但是这个接口的作用是将unicode编码成指定编码的字符串,在str上是无效的。
一个相对复杂的应用:
字符串转unicode在搜索引擎abelkhan 爬虫部分的应用
开源的搜索引擎,欢迎大家支持!
项目地址:http://www.abelkhan.com/
向我们提出意见:http://www.abelkhan.com/guestbook/
对项目进行捐助:http://www.abelkhan.com/collection/
代码托管地址如下:https://github.com/qianqians/websearch欢迎大家参与
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欢迎大家参与
相关文章推荐
- Python reverse order
- Python介绍、环境搭建(Eclipse插件)、第一个程序
- numpy 常用api(四)
- Python 分发工具初探之 setuptools 进阶
- python--类方法、对象方法、静态方法
- Python--类定义
- python 使用 passlib 库在 windows 平台实现 crypt
- Spark机器学习7·降维模型(scala&python)
- Spark机器学习1·编程入门(scala/java/python)
- python 模拟登陆leetcode
- Python环境的安装
- Python碎片小知识点总结
- 自己实现一个Python调试器
- python之2048
- 两篇文章掌握Python语法和内置函数功能(第二篇)
- Python中对字典排序
- python 正则表达式的学习
- python操作Excel读写--使用xlrd
- python 冒号与逗号的区别
- Python学习笔记(三)高级特性