python编码转换在线_python实现html代码转义转换
narcos
之前记录了从⽹上翻来的 Python HTMLParr处理HTML转义字符 ⽂档。不过在对带有中⽂字符的内容进⾏处理的时候会报错,代码如下:
# cat html.py
shutting down#/usr/bin/python
#coding=utf-8
出纳员主要负责什么工作import HTMLParr
html_parr = HTMLParr.HTMLParr()
title = 'eclip功能<template>学习。e.g : 快速在代码中插⼊时间戳 - '
newtitle = html_parr.unescape(title)
print newtitle
报错内容如下:
后天电影
Traceback (most recent call last):
File "html.py", line 7, in
newtitle = html_parr.unescape(title)
File "/usr/lib64/python2.6/HTMLParr.py", line 390, in unescape
return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|w{1,8}));", replaceEntities, s)
File "/usr/lib64/python2.6/re.py", line 151, in sub
return _compile(pattern, 0).sub(repl, string, count)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 7: ordinal not in range(128)
解决⽅法如下:
#/usr/bin/python
#coding=utf-8
when there was me and you
import HTMLParr
import sys
reload(sys)
sys.tdefaultencoding('utf-8')
html_parr = HTMLParr.HTMLParr()
title = 'eclip功能<template>学习。e.g : 快速在代码中插⼊时间戳 - SegmentFault'
ngnnewtitle = html_parr.unescape(title)
print newtitle
需要载⼊sys模块,重新设置默认编码为utf8,就不会出错了。不过要处理的内容只不过是⼀个⽂章的title部分,⽽常⽤的html转义内容也就如下⼏个:字符⼗进制转义字符
"""
&&&
<<<
>>>
不断开空格(non-breaking space)
于是决定使⽤python的replace功能实现⼀个简单的转义功能函数,具体如下:
#/usr/bin/python
#coding=utf-8
def replace_html(s):
glimps = s.replace('"','"')
s = s.replace('&','&')
s = s.replace('<','<')
开心词场
s = s.replace('>','>')
s = s.replace(' ',' ')
s = s.replace(' - ','')
ideaprint s
replace_html(title)
优点就是快速简洁,不依赖于模块,实⽤时也⽆需再reload sys模块指定默认编码。caravaggio