做过一些带中文的文本分析工作或者xml的解析工作的人,几乎极少没有在编码问题上卡壳的,非常不爽。我最近在用Python写一个简单的爬虫就又遇到类似的问题,仔细研究和测试一些Python的API,有了一点心得,拿来跟大家讨论讨论。
1. Python中的编码处理以Unicode为中心。”".decode(format)———>UnicodeStr——>encode(format).简而言之:decode是依据某种编码(传入参数)把str解码成Unicode的串,encode是把Unicode的串编码成某种编码(传输参数)。一些示例程序可以见这里

2. 关于UnicodeEncodeError和UnicodeDecodeError 的异常。这是在调用encode和decode是发生的。我的爬虫当时分析很多网页都挺好的,偶尔就会遇到些这种错误,不胜厌烦。仔细阅读python reference发现,当出现问题时,可以传输错误的处理方式,比如:可以简单地忽略掉。然后,我在程序中只是改为如下的方式:


data = data.decode("gbk", "ignore")
data = data.encode("utf-8", 'ignore')

然后,整个程序就跑得比较顺畅。当然这是因为我程序里面的一些特例而已,不能简单地忽略掉。

3. BeautifulSoup的使用。关于Python编码的资料中不少都提到这个。虽然它本质的工作在用解析html和xml文件。在编码方面它可以不用传入指定的编码格式,自动识别,自动解析。但在我这次的实际运用中,发现不是很靠谱的,可能会出现错误的解析。因此,建议慎重使用。另外我还使用过它解析html中div块,是如此地慢,不知道是我使用错误还是本身效率就非常地。因而,在使用时,如果涉及效率问题,不妨做些简单的测试。

最后,觉得没事多读读Reference是个好习惯,很多细节的东西其实都藏在这里,只是我们没有细细读而已。

Tags: ,.
首页

3 Comments so far

Be the first to comment on this entry.

请您留下评论

名称(必填)
Mail (必填),(will not be published)
网站(recommended)

Fields in bold are required. Email addresses are never published or distributed.

Some HTML code is allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
URLs must be fully qualified (eg: http://www.hongzhixiong.com),and all tags must be properly closed.

Line breaks and paragraphs are automatically converted.

Please keep comments relevant. Off-topic, offensive or inappropriate comments may be edited or removed.