zoukankan      html  css  js  c++  java
  • 序列化


    -------------------失去了昨日的繁星并不可怕,可怕的是你又错过了今天的朝阳。

    # # ------------------------------------------------------------------------------------------------------------#
    day 22 
    import pickle

    #
    # class Dog:
    # def __init__(self, name, size):
    # self.name = name
    # self.size = size
    #
    # def wangwangg(self):
    # print("%s狗会旺旺旺" % self.name)


    # D = Dog("中华城市田园乡村",25)
    #
    # ps = pickle.dumps(D)
    #
    # print(ps)
    #
    # zh = pickle.loads(ps)
    #
    # D.wangwangg()

    # D = Dog("中华城市田园乡村",25)
    #
    # pickle.dump(D,open("cat.txt","wb"))
    #
    # dq = pickle.load(open("cat.txt","rb"))
    #
    # print(dq.name,dq.size)


    # --------------------------------------
    # E = Dog("城市乡村田园", 26)
    # F = Dog("中华田园乡村", 28)
    # G = Dog("中华乡村城市", 23)
    #
    # lst = [E, F, G]
    #
    # f = open("cat.txt", "ab")
    # print(lst, f)


    # --------------------------------------
    # class User:
    # def __init__(self, username, password):
    # self.username = username
    # self.password = password
    #
    #
    # class Admin:
    # def regist(self):
    # uname = input("注册账号-->")
    # pswd = input("密码-->")
    # user =User(uname,pswd)
    # pickle.dump(user,open("list_user","ab"))
    # print("注册成功!")
    #
    # def login(self):
    # uname = input("--登录账号-->")
    # pswd = input("--密码-->")
    # f = open("list_user","rb")
    #
    # while 1:
    # try:
    # u = pickle.load(f)
    # if u.username == uname and u.password == pswd:
    # print("登录成功")
    # break
    # except Exception as e:
    # print("登录失败!")
    # break
    #
    # u1 = Admin()
    # u1.regist()
    # u1.regist()
    #
    # u1.login()
    # ----------------------------------
    # import shelve
    #
    # d = shelve.open("pig") #文件类型的字典
    # d['ajx'] = "阿J斯"
    # d.close()
    #
    # d = shelve.open("pig")
    # print(d['ajx'])
    # d.close()
    #
    # d = shelve.open("pig") #文件类型的字典
    # d['ajx'] = {"name":"阿J斯","age":18}
    # d.close()

    # ----------------------------------
    import json

    # dikt={"A":"西瓜","B":"草莓","C":"香蕉","D":"菠萝"}
    # J = json.dumps(dikt,ensure_ascii=False)
    # print(J)
    # print(type(J))
    # print("*" * 80)
    # s = '{"A":"西瓜","B":"草莓","C":"香蕉","D":"菠萝"}'
    # J1 = json.loads(s)
    # print(J1)
    # print(type(J1))

    # ----------------------------------

    # dikt2 = {"A": "西瓜", "B": "草莓", "C": "香蕉", "D": "菠萝"}
    # f = open("nainiu.json", "w", encoding="utf8")
    # json.dump(dikt2, f, ensure_ascii=False, indent=4)
    #
    # f1 = open("nainiu.json", "w", encoding="utf8")
    # f2 = json.load(f1)
    # print(f2)


    # ----------------------------------
    # class PP:
    # def __init__(self, F_name, L_name):
    # self.F_name = F_name
    # self.L_name = L_name
    #
    #
    # p1 = PP("蒙娜丽莎", "江小白")
    #
    #
    # # 把对象转化成json
    # # s = json.dumps(p1.__dict__, ensure_ascii=False)
    # # print(s)
    #
    # def func(obj):
    # return {
    # "firstName": obj.F_name,
    # "lastName": obj.L_name
    # }
    #
    #
    # # s = json.dumps(p1, default=func, ensure_ascii=False)
    # # print(s)
    #
    #
    # # ----------------------------------
    # s = '{"firstName": "蒙娜丽莎", "lastName": "江小白"}'
    # def funk():
    # return PP(dic["firstName"],dic["lastName"])
    #
    # p = json.loads(s,object_hook=func)
    # print(p.lastName,p.lastName)

    # # ------------------------------------------------------------------------------------------------------------#


    # Day 22 作业

    # 0.整理博客和笔记.
    '''
    序列化 把对象打散成二进制字节 bytes
    1. pickle 把一个对象转化成bytes写入到文件
    pickle.dumps() 把对象转换成bytes
    pickle.loads() 把bytes转化成对象

    pickle.dump() 把对象转换成bytes. 写入到文件
    pickle.load() 把文件中的bytes读取. 转化成对象

    2. shelve 小型数据库, redis, mongodb, dict
    当成字典来用
    writeback=True

    3. json 以前用xml 先在用json
    json.dumps() 把字典转换成json字符串
    json.loads() 把json字符串转化成字典

    json.dump() 把字典转换成json字符串. 写入到文件
    json.load() 把文件中的json字符串读取. 转化成字典

    default = 把对象转化成字典. 需要自己写转换过程
    object_hook = 把字典转化成对象. 需要自己写转换过程

    ensure_ascii = False 可以处理中文


    4. configparser 处理windows配置文件的 dict

    '''
    # # ------------------------------------------------------------------------------------------------------------#

    # 1.随机生成4位验证码(包含数字, 字母)

    import string
    import random
    #
    # Up = string.ascii_uppercase
    # Lw = string.ascii_lowercase
    # Nu = string.digits
    #
    # D_num = random.randint(1,2)
    # L_num = random.randint(1, 4-D_num - 1)
    # N_num = 4 - (D_num + L_num)
    # password = random.sample(Up, D_num)+random.sample(Lw, L_num)+random.sample(Nu, N_num)
    # random.shuffle(password)
    # print(password)


    # # --------------*******--------------
    # lst = []
    # for i in range(48,58):
    # lst.append(chr(i))
    #
    # for i in range(ord("a"),ord("z")+1):
    # lst.append(chr(i))
    #
    # for i in range(ord("A"),ord("Z")+1):
    # lst.append(chr(i))
    #
    # print(lst)
    # for i in range(100):
    # # print(random.sample(lst,8))
    # print()
    # for i in random.sample(lst,4):
    # print(i,end="")


    # # ------------------------------------------------------------------------------------------------------------#

    # 2.模拟发红包. 不需要考虑权重问题. 纯随机.xxx
    # 例如, 小红发了100块红包. 发给30人. 请给出每个人能收到的钱数
    # money = 100
    # person = 3
    #
    # import random
    # n = random.random()
    # m =random.random() * 100 #(0,1) ->(0,100)
    # s = int(m * n)
    # print(s)

    # # --------------*******--------------
    # import random
    # def hongbao(money,p):
    # lst=[]
    # d_money=0
    # for i in range(1,p):
    # t=random.randint(1,(money-d_money)-(p-i))
    # lst.append(t)
    # d_money=d_money+t
    # lst.append(money-d_money)
    # return lst
    #
    # money=100
    # p=3
    # for i in range(3):
    # lst=hongbao(money,p)
    # print(lst)
    # # ------------------------------------------------------------------------------------------------------------#

    # 3.完善昨天最后一题. 把对象通过pickle写入到文件中.

    # # ------------------------------------------------------------------------------------------------------------#

    # 4.(升级题))请从以下网址获取json数据. 并对json进行分析. 获取到每家店的[名称]以及[特色菜], 并把获取到的店名和特色菜写入到文件中:
    # https://h5.ele.me/restapi/shopping/v2/restaurants/search?offset=15&limit=15&keyword=%E7%8C%AA%E8%B9%84&latitude=39.904172&longitude=116.407417&search_item_type=3&is_rewrite=1&extras[]=activities&extras[]=coupon&terminal=h5
    # 温馨提示. 首先在chrome地址栏中输入以上网址. 然后把显示的所有内容复制. 按F12 找到屏幕中的console. 粘贴进去. 回车 就能看到数据了.此题需要用到urllib.request模块中的urlopen

    import json
    from urllib.request import urlopen

    ul = urlopen(
    "https://h5.ele.me/restapi/shopping/v2/restaurants/search?offset=0&limit=15&keyword=%E7%8C%AA%E8%B9%84&latitude=22.583743&longitude=113.968537&search_item_type=3&is_rewrite=1&extras[]=activities&extras[]=coupon&terminal=h5").read()

    str = ul.decode("utf-8")

    dickt = json.loads(str)

    lst = dickt['inside']['0']['restaurant_with_foods']

    for i in lst:

    print(i['restaurant']['name'])

    for j in i['foods']:
    print(j['name'])

    # # ------------------------------------------------------------------------------------------------------------#
    #
    # 明日默写内容.
    # 使用json模块完成:
    # 1.字典-> 字符串
    # 2.字符串 -> 字典
  • 相关阅读:
    D. Babaei and Birthday Cake--- Codeforces Round #343 (Div. 2)
    Vijos P1389婚礼上的小杉
    AIM Tech Round (Div. 2) C. Graph and String
    HDU 5627Clarke and MST
    bzoj 3332 旧试题
    codeforces 842C Ilya And The Tree
    codesforces 671D Roads in Yusland
    Travelling
    codeforces 606C Sorting Railway Cars
    codeforces 651C Watchmen
  • 原文地址:https://www.cnblogs.com/dealdwong2018/p/9966955.html
Copyright © 2011-2022 走看看