python 解析unicode编码的字符串

使用python抓取页面或者web端的json时候很容易抓到一些unicode编码的字符串流。在python里边对Unicode编码的处理成了一件头疼的事。 html

对于string里边不含“ 引号的处理比较简单,使用eval注明引入str是unicode编码: python

str1 = eval("u"+"\""+str + "\"")

str1.decode('utf8')

对于包含引号的明文,须要先把引号转化为 \",而后能够进行eval函数处理。 web

str=str.replace("\\\"","\\\\\"") #先转化字符串中的\"
str=str.replace("\"","\\\"")     #再转化 "

print eval("u"+"\""+str+"\"")

对于json格式unicode的有个很奇怪的处理 json

python 的json 库在使用 json.loads()函数时候会默认把输入中unicode编码解析好,而不是保留原输入。 函数

代码: 编码

str1="{\"html\":\"\u003c\u003e\"}"
s=json.loads(str1)
print s["html"]
输出:<>

输出<>而不是 \u003c 这也引出了一个问题:python的json库解析json不彻底保留原格式,使用时候要注意。 spa

若是想要json解析保持unicode编码比较麻烦,须要将unicode码的\改成\\,转译代码以下: code

str="{\"html\":\"\u003c\"}"
s=str.replace("\\u","\\\\u")
s2=json.loads(s)
print s2["html"]
输出: \u003c
相关文章
相关标签/搜索