首页 > 编程语言 >辨别 Python 中 load 和 loads 的小技巧

辨别 Python 中 load 和 loads 的小技巧

时间:2022-10-10 23:08:54浏览次数:81  
标签:load info cinema Python list json loads hall

 

 

load 和 loads 都是实现“反序列化”,load 通过 json.load(open('*.json')) 这样的格式,从文件句柄中打开文件,加载到Python的变量中,并以字典的格式转换。而 loads 必须对于 Python内存中的序列化对象转换成字符串。

load 和 loads 都是实现 “反序列化”,区别在于(以Python为例):

  • loads 针对 内存对象,即将 Python内置数据序列化为字串。如使用json.dumps序列化的对象d_json=json.dumps({'a':1, 'b':2}),在这里 d_json 是一个字串'{"b": 2, "a": 1}',d=json.loads(d_json)  #{ b": 2, "a": 1},使用load重新反序列化为dict
  • load 针对 文件句柄​。如本地有一个 json 文件 a.json 则可以 d=json.load(open('a.json')),相应的,dump 就是将内置类型序列化为 json 对象后写入文件

 

测试 ( 使用 loads )


list_1 = '[1,2,3,4]'
dict_1 = '{"k1":"v1"}'
print(type(list_1)) # <class 'str'>
print(type(dict_1)) # <class 'str'>


ret = json.loads(list_1)
print(ret, type(ret))

ret = json.loads(dict_1)
print(ret, type(ret))

# 输出
# [1, 2, 3, 4] <class 'list'>
# {'k1': 'v1'} <class 'dict'>

 

测试( 使用 load ):

# -*- coding: utf-8 -*-
# @Time :
# @Author :
# @Email :
# @File : parse_cinema_info.py
# @Software: PyCharm


import json


def parse_cinema_info():
cinema_info_dict = json.load(open('f:/bj_cinema_all_info.json', "rb"))
all_cinemas = cinema_info_dict['cinemas']
cinemas_list = list()
for cinema in all_cinemas:
d = dict(
cinema_id=cinema['id'],
cinema_name=cinema['nm'],
city='北京',
address=cinema['addr'],
telephone=None
)
cinemas_list.append(d)
with open('f:/bj_cinema.json', 'w') as f:
json.dump(cinemas_list,f, ensure_ascii=False, indent=4)
pass


if __name__ == '__main__':
parse_cinema_info()
pass

使用 dump:

# -*- coding: utf-8 -*-
# @Time :
# @Author :
# @Email :
# @File : parse_cinema_hall_info.py
# @Software: PyCharm

import re
import json


def parse_file():
cinema_hall_info = dict()
with open('f:/pipelines.log', 'rb') as f:
all_lines = f.readlines()
for line in all_lines:
line_str = line.decode('utf-8')
base_time_info = re.findall("\('.*?'\)", line_str)
if base_time_info:
hall_info_list = list()
for base_time in base_time_info:
t = tuple(eval(base_time))
cinema_id, hall_info = t[1], t[8]
if hall_info not in hall_info_list:
hall_info_list.append(hall_info)
cinema_hall_info[cinema_id] = hall_info_list
else:
# print(json.dumps(cinema_hall_info, ensure_ascii=False))
hall_info_list = list()
for cinema in cinema_hall_info:
# print('cinema_id : {0} hall_info : {1}'.format(cinema, cinema_hall_info[cinema]))
d = dict(
cinema_id=cinema,
hall_info=cinema_hall_info[cinema],
seat_count=None
)
hall_info_list.append(d)
else:
with open('f:/bj_cinema_hall.json', 'w') as f:
json.dump(hall_info_list, f, ensure_ascii=False, indent=4)


if __name__ == '__main__':
parse_file()
pass

一个测试 json 文件 (bj_cinema_all_info.json):

{
"cinemas": [
{
"id": 264,
"mark": 0,
"nm": "万达国际影城(CBD店)",
"sellPrice": "48.5",
"addr": "朝阳区建国路93号万达广场B座3层",
"distance": "600m",
"tag": {
"allowRefund": 0,
"buyout": 0,
"cityCardTag": 0,
"deal": 0,
"endorse": 0,
"hallType": [
"IMAX厅",
"RealD 6FL厅",
"4DX厅"
],
"hallTypeVOList": [
{
"name": "IMAX厅",
"url": ""
},
{
"name": "RealD 6FL厅",
"url": ""
},
{
"name": "4DX厅",
"url": ""
}
],
"sell": 1,
"snack": 1,
"vipTag": "折扣卡"
},
"promotion": {

}
},
{
"id": 23,
"mark": 0,
"nm": "百丽宫影城(国贸店)",
"sellPrice": "29",
"addr": "朝阳区建国门外大街1号国贸商城北区B1层B120",
"distance": "1km",
"tag": {
"allowRefund": 0,
"buyout": 0,
"cityCardTag": 0,
"deal": 0,
"endorse": 0,
"hallType": [
"RealD厅"
],
"hallTypeVOList": [
{
"name": "RealD厅",
"url": ""
}
],
"sell": 1,
"snack": 1
},
"promotion": {

}
}
],
"ct_pois": [
{
"ct_poi": "936879945111165696_a15272_c223",
"poiid": 99082156
},
{
"ct_poi": "936879945111165696_a2378_c224",
"poiid": 1541434
},
{
"ct_poi": "936879945111165696_a15748_c225",
"poiid": 94728699
}
],
"paging": {
"hasMore": false,
"limit": 10000,
"offset": 0,
"total": 226
}
}

 

 

 



标签:load,info,cinema,Python,list,json,loads,hall
From: https://blog.51cto.com/csnd/5745417

相关文章

  • Python 日期 的 加减 等 操作
     datetime—Basicdateandtimetypes:​​https://docs.python.org/3.8/library/datetime.html​​dateutil---powerfulextensionstodatetime:​​https://dateutil......
  • 怎么可以少了“雪融融”呢?python在画一个雪蓉蓉陪着“冰墩墩”
    公众号ID|ComputerVisionGzq学习群|扫码在主页获取加入方式计算机视觉研究院专栏作者:Edison_G冬奥会如火如荼的举行中,吉祥物之一的冰墩墩特别抢手!身为程序员,已经拥有一个“虚......
  • LMS Virtual.Lab二次开发:声学仿真理论基础准备(Python)
    1、简介采用LMSVirtual.LabAcoustics声学软件,可以直接打开CATIAV5的设计模型、或者间接导入其它CAD软件的三维模型,实现从声学模型创建、复杂边界条件加载、快速求解计算......
  • python词云剔除非有效词
    title:python词云剔除非有效词excerpt:python爬虫小作业2.0tags:[python,词云,爬虫]categories:[学习,python]index_img:https://picture-store-repository.......
  • CentOS7下安装python3.8卸载3.6
    title:CentOS7下安装python3.8卸载3.6excerpt:VM记得拍快照!拍快照!快照!tags:[语音识别,kaldi,python3,python2,centos7]categories:[学习,python][学习,语......
  • python的基本运用
    python基础Python语言是一种解释型、面向对象、动态数据类型的高级程序设计语言开发者:GuidovanRossum(人称龟叔)基本概念1.变量变量名必须是大小写英文字母、数字或下......
  • Python 应用之求 100 以内的奇数和
    在数学中,我们需要用到很多求和的办法,比如说求1至100的和,还有100以内的所有偶数和和所有奇数和,如果我们慢慢地计算是不是很浪费时间,还容易出错。其实通过Python就可......
  • 【Azure 应用服务】Python Function App重新部署后,出现 Azure Functions runtime is u
    问题描述PythonFunctionApp重新部署后,出现AzureFunctionsruntimeisunreachable错误 问题解答在FunctionApp的门户页面中,登录Kudu站点(https://<yourfunction......
  • python中reload(sys)详解
    问题python在安装时,默认的编码是ascii,当程序中出现非ascii编码时,python的处理常常会报错UnicodeDecodeError:‘ascii’codeccan’tdecodebyte0x??inposition1:o......
  • python opencv画矩形框保存xml和读取显示
     参考图书馆空位检测(行人+空位对比)https://www.cnblogs.com/gooutlook/p/16192389.html  使用到的原始图像       1鼠标选择画框API_draw.py......