数据分类
非结构化数据:html等
处理方法:正则表达式,xpath
结构化数据:json,xml
处理方法:转化位python数据类型
JSONView的使用:
安装JSONView插件
下载插件,拖入chrome://extensions/这个网页里就可以用了
美化输出-格式化pprint
from pprint import pprint with open("douban.json", "r") as f: html_str = f.read() ret1 = json.loads(html_str)
print(ret1) pprint(ret1)
结果:
# print打印结果
{'err_no': 0, 'csor': '0', 'bs': '', 'p': False, 'errmsg': '', 'g': [{'type': 'his_normal', 'sa': 'h_1', 'q': '豆瓣'}, {'type': 'his_normal', 'sa': 'h_2', 'q': 'aptget使用方法'}, {'type': 'his_normal', 'sa': 'h_3', 'q': 'wget使用方法'}, {'type': 'his_normal', 'sa': 'h_4', 'q': 'wget安装'}, {'type': 'his_normal', 'sa': 'h_5', 'q': 'retrying python'}, {'type': 'his_normal', 'sa': 'h_6', 'q': 'retrying用法'}, {'type': 'his_normal', 'sa': 'h_7', 'q': 'python字符串转化列表'}, {'type': 'his_normal', 'sa': 'h_8', 'q': '在线翻译'}, {'type': 'his_normal', 'sa': 'h_9', 'q': '必应翻译在线翻'}, {'type': 'his_normal', 'sa': 'h_10', 'q': '必应翻译'}], 'q': ''} # pprint打印结果
{'bs': '', 'csor': '0', 'err_no': 0, 'errmsg': '', 'g': [{'q': '豆瓣', 'sa': 'h_1', 'type': 'his_normal'}, {'q': 'aptget使用方法', 'sa': 'h_2', 'type': 'his_normal'}, {'q': 'wget使用方法', 'sa': 'h_3', 'type': 'his_normal'}, {'q': 'wget安装', 'sa': 'h_4', 'type': 'his_normal'}, {'q': 'retrying python', 'sa': 'h_5', 'type': 'his_normal'}, {'q': 'retrying用法', 'sa': 'h_6', 'type': 'his_normal'}, {'q': 'python字符串转化列表', 'sa': 'h_7', 'type': 'his_normal'}, {'q': '在线翻译', 'sa': 'h_8', 'type': 'his_normal'}, {'q': '必应翻译在线翻', 'sa': 'h_9', 'type': 'his_normal'}, {'q': '必应翻译', 'sa': 'h_10', 'type': 'his_normal'}], 'p': False, 'q': ''}
json和python数据格式互换
from pprint import pprint import json with open("douban.json", "r", encoding="utf-8") as f: html_str = f.read() # json.loads把json字符串转化为Python的字典类型 print(type(html_str)) # str格式 ret1 = json.loads(html_str) print(type(ret1)) # dict格式 # json.dumps 能把python类型转化为json字符串 with open("douban-1.json", "w", encoding="utf-8") as f: f.write(json.dumps(ret1, ensure_ascii=False, indent=2)) # ensure_ascii=False关闭askii码格式 indent=2格式化输出 下一级跟上一级缩进2格 # json.load 提取类文件对象的数据直接转化成python数据类型 with open("douban.json", "r") as f: ret2 = json.load(f) print(ret2) print(type(ret2)) # json.dump() 能够把python数据类型放入类文件对象中 with open("douban-2.json", "w", encoding="utf-8") as f: json.dump(ret1, f, ensure_ascii=False, indent=2)
结果