美文网首页
day13总结

day13总结

作者: xue_y | 来源:发表于2019-01-09 20:59 被阅读0次

    json

    1.什么是json数据
    json是一种具有特定语法的数据格式

    2.json数据的语法
    一个json数据有且只有一个数据, 这个数据的数据类型必须是json支持的数据类型

    3.json支持的数据类型
    a.数字类型: 包含所有的数字,包括整数、小数;例如: 100, 12.5, -3.14
    注意:1)整数前面不能加'+'
       2)支持科学计数法: 3e2
    b.字符串: 使用双引号括起来的数据; 例如:"abc", "abc123,!"
    c.布尔: 只有true和false两个值
    d.数组: 相当于python的列表,用[]括起来,多个元素用逗号隔开;例如: [100, "abc", [1, 2]]
    e.字典: 相当于python的字典, 用{}括起来,多个键值对用逗号隔开, 例如:{"a": 10, "b": 20, "c": [1, 3]}
    f.空值: null,相当于python中的None

    4.python处理json数据
    python中提供了json模块,专门用来处理json数据

    1. 将json数据转换成python数据(通过爬虫获取到别人提供的json数据,在python中处理)
      a.转换方式
    json python
    数字 int/float
    字符串 str, 可能双引号会变成单引号
    布尔 bool, 会将json中的true/false转换成True/False
    数组 list
    字典 dict
    空值(null) None

    b.loads方法
    loads(字符串, encoding='utf-8') - 将字符串中的json数据转换成对应的python数据
    !!!!!!!!注意: 这儿的字符串中!!!内容!!!!必须json数据

     # 将json中的字符串转换成python数据
        content = json.loads('"abc"', encoding='utf-8')
        print(content, type(content))   # abc <class 'str'>
    
        # 将json中的数字转换成python数据
        content = json.loads('100', encoding='utf-8')
        print(content, type(content))
    
        # 将json中的字典转换成python数据
        message = '{"name": "张三", "age": 18, "sex": null, "marry": true}'
        content = json.loads(message, encoding='utf-8')
        print(content, type(content))
        print(content['name'])
    

    2将python数据转换成json数据(python写后台接口将数据提供给客户端)
    a.转换方式

    python json
    int/float 数字
    str 字符串,单引号会变成双引号
    bool True->true;False->false
    list/tuple 数组
    dict 字典
    None null

    b.dumps(对象) - 将指定的对象转换成json数据, 以字符串的形式返回
    这儿的对象指的就是python数据
    注意: 返回值是字符串,并且字符串的!!!!内容!!!!是json数据

    result = json.dumps(100.23)
        print(type(result), result)    # '100.23'
    
        result = json.dumps('abc')
        print(type(result), result)  # '"abc"'
    
        result = json.dumps(True)
        print(type(result), result)  # 'true'
    
        result = json.dumps([10, 'abc', True, None])
        print(type(result), result)  # '[10, "abc", true, null]'
    
        result = json.dumps((10, 'abc', True, None))
        print(type(result), result)  # '[10, "abc", true, null]'
    
        result = json.dumps({'a': 10, 'b': 'abc', 'c': True, 'd': None})
        print(type(result), result)  # '{"a": 10, "b": "abc", "c": true, "d": null}'
    
        # 集合不能转换成json数据
        # result = json.dumps({10, 'abc', True, None})
        # print(type(result), result)  # '[10, "abc", true, null]'
    

    5.json文件处理
    严格来说,json文件是文件内容是json数据的文件

    load(文件对象) - 将指定文件中的内容读出来,并且转换成python对应的数据。
    注意:这儿的文件对象对应的文件必须是json文件

        with open('data.json', encoding='utf-8') as f:
            result = json.load(f)   # 相当于 result = json.loads(f.read())
            print(type(result), result['msg'])
    

    dump(对象, 文件对象) - 将指定对象转换成内容是json格式的字符串,然后写入指定的文件中
    注意:这儿的对象对应的类型必须是能够转换成json的数据类型

        all_student = [
            {'name': '小明', 'age': 12, 'tel': '1237736'},
            {'name': 'yuting', 'age': 18, 'tel': '23333'},
            {'name': 'Luffy', 'age': 20, 'tel': None},
            {'name': 'zuoLuo', 'age': 30, 'tel': '923736'},
        ]
        with open('student.json', 'w', encoding='utf-8') as f:
            json.dump(all_student, f)  # 相当于 f.write(json.dumps(all_student))
    

    练习题
    用一个列表保存多个学生的信息.写函数向这个列表中添加学生(姓名、年龄、成绩)。
    要求之前添加过的学生,下次运行程序的时候还在

    import json
    
    
    def add_student(list1: list):
        name = input('姓名:')
        age = int(input('年龄:'))
        score = float(input('成绩:'))
        list1.append({'name': name, 'age': age, 'score': score})
    
    
    def main():
        # 获取数据
        # all_student = []
        with open('allStudent.json', encoding='utf-8') as f:
            all_student = json.load(f)
            # all_student = [{}, {}]
    
        add_student(all_student)
        add_student(all_student)
        # all_student = [{}, {}, {}, {}]
    
        # 更新数据
        with open('allStudent.json', 'w', encoding='utf-8') as f:
            json.dump(all_student, f)
    
        print(all_student)
    
    
    if __name__ == '__main__':
        main()
    

    数据请求

    python中的数据请求(http请求),是第三方库requests来提供的

    1.requests第三方库的使用
    get/post方法都是发送请求获取接口提供的数据

    a.get(url, params=None)
    url - 字符串,需要获取的数据的接口地址
    params - 字典,参数列表(给服务器发送请求的时候需要传给服务器的数据)
    https://www.apiopen.top/meituApi?page=1
    完整的接口: 协议://主机地址/路径?参数名1=值1&参数名2=值2

    # 1.发送请求,并且获取返回的数据
        # 服务返回的数据叫响应
        response = requests.get('https://www.apiopen.top/meituApi?page=1')
        # response = requests.get('https://www.apiopen.top/meituApi', {'page': 1})
        print(response)
    
        # 2.从响应中获取数据
        # a.获取json数据
        content_json = response.json()   # 会自动将json数据转换成python对应的数据
        print(type(content_json))
        print(content_json)
    
        # b.获取字符串数据
        content_text = response.text
        print(type(content_text))
        print(content_text)
    
        # c.获取二进制数据(原始数据)
        content_bytes = response.content
        print(content_bytes)
    
        # 下载图片
        response2 = requests.get('http://tx.haiqq.com/uploads/allimg/170506/0H92Q915-1.jpg')
        with open('luffy.jpg', 'wb') as f:
            f.write(response2.content)
    

    b.post(url, params=None, json=None)(暂时不管!)

    异常捕获

    1.异常捕获 - 让本该报错的代码不报错
    你知道某段代码会出现异常,而且没有办法避免,同时又希望出现异常的时候程序不崩溃;
    这个时候就可以通过异常捕获,来让程序不崩溃并且自行处理异常
    2.异常捕获语法
    a. try-except (可以捕获所有类型的异常 - 只要代码段1中出现了异常就捕获)
    try:
       代码段1(可能会出现异常的代码段)
    except:
      代码段2(出现异常后处理异常的代码段)

    ef method1():
        print('==============1.try-except===========')
        # try:
        #     number = int(input('请输入一个数字:'))
        #     print(number)
        # except:
        #     print('出现异常,输入有误!')
    
        try:
            print('abc'[4])   # IndexError
            print('=======')
            print({'a': 10}['b'])  # KeyError
        except:
            print('出现异常!')
    

    b. try - except 错误类型 (捕获指定类型的异常 - 只有代码段1中出现了指定类型的异常才捕获)
    try:
       代码段1(可能会出现异常的代码段)
    except 错误类型:
      代码段2(出现异常后处理异常的代码段)

    def method2():
        print('==============2.try-except 错误类型===========')
        try:
            print({'a': 100}['b'])  # KeyError
            print(a)
            print([1, 2, 3][4])  # IndexError
        except (KeyError):
            print('出现异常')
    

    c.try - except (错误类型1,错误类型2...) (同时捕获多种指定异常)
    try:
       代码段1(可能会出现异常的代码段)
    except (错误类型1,错误类型2...):
       代码段2(出现异常后处理异常的代码段)

    def method2():
        print('==============2.try-except 错误类型===========')
        try:
            print({'a': 100}['b'])  # KeyError
            print(a)
            print([1, 2, 3][4])  # IndexError
        except (KeyError, IndexError):
            print('出现异常')
    

    d.try-except 错误类型1 - except 错误类型2... (同时捕获多种异常,可以对不同的异常做不同的处理)
    try:
    代码段1(可能会出现异常的代码段)
    except 错误类型1:
    代码段2
    except 错误类型2:
    代码段3
    ...

    def method3():
        print('==============2.try-except 错误类型1-except 错误类型2...===========')
        try:
            with open('abc.txt', 'r') as f:
                print(f.read())
            print({'a': 100}['b'])  # KeyError
        except KeyError:
            print('key不存在')
        except FileNotFoundError:
            print('文件不存在!')
    
        print('~~~~~~~~~')
    

    3.抛出异常 - 主动让程序奔溃
    raise 错误类型 - 程序执行到这句代码就出现指定类型的异常!
    说明:错误类型 - 可以是系统提供的错误类型, 也可以是自定义错误类型(要求这个值必须是一个类,而且是Exception的子类)

    # 自定义错误类型
    class YTValueError(Exception):
        def __str__(self):
            return '给的值不满足要求!'
    
    

    相关文章

      网友评论

          本文标题:day13总结

          本文链接:https://www.haomeiwen.com/subject/fxagrqtx.html