• 【Python31--pickle函数】


    一、含义

    1、pickle的实质是什么

    答:利用一些算法把数据对象转换成“二进制文件”,存储在硬盘上,当然也可以放在数据库或者是另外一台计算机上

    2、存放:picking,读取:unpicking

    3、把my_list 的数据放到pickle_file文件内

    >>> import pickle
    >>> my_list = [123,3.14,'尘封',['another list']]
    >>> pickle_file = open('my_list.pkl','wb')
    >>> pickle.dump(my_list,pickle_file)   #dump():把my_list的数据放到pickle_file文件内
    >>> pickle_file.close()
    #把写入硬盘的数据在读取出来(用到load函数)
    >>> pickle_file = open('my_list.pkl','rb')
    >>> my_list2 = pickle.load(pickle_file)
    >>> print(my_list2)
    [123, 3.14, '尘封', ['another list']]
    >>> 

    4、天气查询接口

    用中国天气网的接口:http://m.weather.com.cn/data/城市代码.html,然后就是用key找value,在打印出来

    接口:http://wthrcdn.etouch.cn/weather_mini?city=北京
    返回的结果:
    {"desc":"OK","status":1000,"data":{"wendu":"22","ganmao":"风较大,较易发生感冒,注意防护。","forecast":[{"fengxiang":"北风","fengli":"5-6级","high":"高温 24℃","type":"","low":"低温 11℃","date":"3日星期六"},{"fengxiang":"北风","fengli":"4-5级","high":"高温 19℃","type":"","low":"低温 8℃","date":"4日星期日"},{"fengxiang":"无持续风向","fengli":"微风","high":"高温 21℃","type":"","low":"低温 9℃","date":"5日星期一"},{"fengxiang":"无持续风向","fengli":"微风","high":"高温 21℃","type":"多云","low":"低温 10℃","date":"6日星期二"},{"fengxiang":"无持续风向","fengli":"微风","high":"高温 24℃","type":"","low":"低温 12℃","date":"7日星期三"},{"fengxiang":"无持续风向","fengli":"微风","high":"高温 23℃","type":"","low":"低温 11℃","date":"8日星期四"}],"yesterday":{"fl":"微风","fx":"无持续风向","high":"高温 23℃","type":"","low":"低温 12℃","date":"2日星期五"},"aqi":"59","city":"北京"}}
    ***********************************************
    代码编写依据返回的结果来确定参数
    import urllib.request
    import gzip
    import json
    
    print('-----------天气查询---------------')
    def get_weather_data():
        city_name = input('请输入城市名称:')
        #url_name:输入城市名(其中urllib.parse.quote是将城市名转换为url的组件),url_cityKey:输入城市代码
        url_name = 'http://wthrcdn.etouch.cn/weather_mini?city='+urllib.parse.quote(city_name)
        #url_cityKey = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100'
    
        #读取网页数据,
        weather_data = urllib.request.urlopen(url_name).read()
        #解压网页数据:
        weather_data = gzip.decompress(weather_data).decode('utf-8')
        #将json数据转换为dict数据
        weather_dict= json.loads(weather_data)
    
        return weather_dict
    
    #定义当前天气输出格式
    def show_weather(weather_data):
        weather_dict = weather_data
        if weather_dict.get('desc') == 'invilad-citykey':
            print('你输入的城市有误或者天气中心未收录你所在城市')
        elif weather_dict.get('desc') == 'OK':
            forecast = weather_dict.get('data').get('forecast')
            print('城市:',weather_dict.get('data').get('city'))
            print('温度:',weather_dict.get('data').get('wendu')+'')
            print('风向:',forecast[0].get('fengxiang'))
            print('分级:',forecast[0].get('fengli'))
            print('高温:',forecast[0].get('hign'))
            print('低温',forecast[0].get('low'))
            print('天气:',forecast[0].get('type'))
            print('日期:',forecast[0].get('date'))
            print('*******************************')
    
            four_day_forecast = input('是否显示未来四天的天气!')
            if four_day_forecast == 'yes'or'YES'or'Yes':
                for i in range(1,5):
                    print('日期:', forecast[i].get('date'))
                    print('温度:', weather_dict.get('data').get('wendu') + '')
                    print('风向:', forecast[i].get('fengxiang'))
                    print('分级:', forecast[i].get('fengli'))
                    print('高温:', forecast[i].get('high'))
                    print('低温:', forecast[i].get('low'))
                    print('---------------------------------')
            print('********************************************')
    
    show_weather(get_weather_data())

    5、使用pickle的什么方法存储数据

    pickle.dump(data.file) (data:待存储的数据对象,file:目标存储的文件对象,注意:在使用这个函数之前先使用open文件和‘wb’)

    6、使用pickle的什么方法读取数据

    pickle.load(file) (参数是目标存储的文件对象,注意要先使用‘rb’的open文件)

    7、编写一个程序,这次要求使用pickle将文件(record.txt)里的对话按照以下要求腌制成不同文件

    #小甲鱼的对话单独保存为boy_*.txt的文件(去掉“小甲鱼:”)

    #小客服的对话单独保存期girl_*.txt的文件(去掉“小客服:”)

    #文件中共有三段对话,分别保存为boy_1.txt,girl_1.txt,boy_2.txt,girl_2.txt,boy_3.txt,girl_3.txt共6个文件(提示:文件中不同的对话间已经使用“===========”分割)

    import pickle
    
    def save_file(boy,gril,count):
    
        boy_file_name = 'boy'+str(count)+'.txt'
        gril_file_name = 'gril'+str(count)+'.txt'
    
        boy_file = open(boy_file_name,'wb')
        gril_file = open(gril_file_name,'wb')
    
        pickle.dump(boy,boy_file)
        pickle.dump(gril,gril_file)
    
        boy_file.close()
        gril_file.close()
    
    
    def open_file(file_name):
        count = 0
        boy = []
        gril = []
    
        f = open(file_name)
    
        for each_line in f:
            if each_line[:6]!= '========':
                (role,each_spken) = each_line.split(':',1)
                if role == '小甲鱼':
                    boy.append(each_spken)
                if role == '小客服':
                    gril.append(each_spken)
                else:
                    save_file(boy, gril, count)
    
                    boy = []
                    gril = []
                    count += 1
    
        save_file(boy, gril, count)
        f.close()
    
    open_file('record.txt')

     

  • 相关阅读:
    大二(上期)学期末个人学习总结
    《梦断代码》阅读笔记01
    软件工程概论课程评价
    03《构建之法》阅读笔记第三篇(终结篇)
    02《构建之法》阅读笔记第二篇
    个人简评——2345王牌拼音输入法
    《人件集》阅读笔记第一篇
    个人学习进度条
    AcWing ST算法(区间求最值)打卡
    AcWing 101. 最高的牛 (差分) 打卡
  • 原文地址:https://www.cnblogs.com/frankruby/p/9492503.html
Copyright © 2020-2023  润新知