编码和解码问题解决

  • Python2和Python3编码声明
# Python2

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# Python3

# coding:utf-8
  • gbk编码转utf-8
s.decode('gbk', 'ignore').encode('utf-8')
  • 爬取网页后出现乱码
# 爬取网页后出现乱码
# res.apparent_encoding是一个字符串可以为utf-8。
res.encoding = res.apparent_encoding
res.encoding = 'utf-8'
  • \xe6 编码格式
a = '\xe6\x93\x8d\xe4\xbd\x9c\xe6\x88\x90\xe5\x8a\x9f'
print(a.encode('raw_unicode_escape').decode())
  • URL格式转中文
from urllib import parse

# 角色扮演
a = '%E8%A7%92%E8%89%B2%E6%89%AE%E6%BC%94'
print(parse.unquote(a))
  • \u('unicode-escape’格式)转中文
a = '\u5f88\u62b1\u6b49\uff0c\u53d1\u751f\u9519\u8bef'
print(a.encode('utf-8').decode())
print(a, type(a))

b = '测试'
print(b.encode('unicode-escape').decode('utf-8'))

# 正则匹配到 表情 然后解码
pattern2 = re.compile(r'"node":\{"id":(.+?),"text":"([\s\S]+?)","created_at')
str_1 = pattern2.findall(a)
# print(str_1)
for str in str_1:
    a, b = str
    print(b.encode('unicode-escape').decode())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值