Python爬取Unicode编码遇到AttributeError: ‘str‘ object has no attribute ‘decode‘

前言:使用Python爬取某网站数据,内容是unicode编码的,用正则表达式截取成如下list保存

li = ['\\u97ea', '\\u867e', '\\u662f', '\\u9898', '\\u76ee', '\\u9898', '\\u5319']

打算解码成中文时出现了错误AttributeError: 'str' object has no attribute 'decode'

因为正则表达式提取的结果都是字符串,而字符串没有decode()方法,所以需要先编码成bytes类型再解码,code如下

s = '\\u662f'
print(s.encode().decode('unicode_escape'))
'''
是
'''

本任务中处理方式如下:

li = ['\\u97ea', '\\u867e', '\\u662f', '\\u9898', '\\u76ee', '\\u9898', '\\u5319']
# 使用 map 和匿名函数批处理
a = list(map(lambda x:x.encode().decode('unicode_escape'), li))
print(a)
'''
['韪', '虾', '是', '题', '目', '题', '匙']
'''

猜你喜欢

转载自blog.csdn.net/UCB001/article/details/121455812