zoukankan      html  css  js  c++  java
  • python 之 random 模块、 shutil 模块、shelve模块、 xml模块

    6.12 random 模块

    print(random.random())(0,1)----float大于0且小于1之间的小数
    print(random.randint(1,3)) [1,3] 大于等于1且小于等于3之间的整数
    print(random.randrange(1,3)) [1,3) 大于等于1且小于3之间的整数
    print(random.choice ( [1,'23', [4,5] ] ) )   1或者23或者[4,5]
    print(random.sample( [1,'23', [ 4,5 ] ] , 2 ) ) 第二个参数是任意几个元素组合 列表元素任意2个组合
    print(random.uniform(1,3)) (1,3) 大于1小于3的小数,如1.927109612082716
    import random
    item=[1,3,5,7,9]
    random.shuffle(item) # 打乱item的顺序,相当于"洗牌"
    print(item)

    6.121 生成随机验证码

    import random
    def make_code(n=5):
        res=''
        for i in range(n):
            s1=str(random.randint(0,9))
            s2=chr(random.randint(65,90))
            res+=random.choice([s1,s2])
        return res
    ​
    print(make_code(10))

    6.13 shutil 模块

    import shutil
    import time
    ret = shutil.make_archive(                          # 压缩
        "day15_bak_%s" %time.strftime('%Y-%m-%d'),
        'gztar',
        root_dir=r'D:codeSH_fullstack_s1day15'
    )
    ​
    import tarfile                                      # 解压
    t=tarfile.open('day15_bak_2018-04-08.tar.gz','r')
    t.extractall(r'D:codeSH_fullstack_s1day16解包目录')
    t.close()

    6.14 shelve模块

    shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写 ;key必须为字符串,而值可以是python所支持的数据类型

    import shelve
    info1={'age':18,'height':180,'weight':80}
    info2={'age':73,'height':150,'weight':80}
    ​
    d=shelve.open('db.shv')     #
    d['egon']=info1
    d['alex']=info2
    d.close()
    ​
    ​
    d=shelve.open('db.shv')     #
    print(d['egon'])        #{'age': 18, 'height': 180, 'weight': 80}
    print(d['alex'])        #{'age': 73, 'height': 150, 'weight': 80}
    d.close()
    ​
    ​
    d=shelve.open('db.shv',writeback=True)  #
    d['alex']['age']=10000
    print(d['alex'])        #{'age': 10000, 'height': 150, 'weight': 80}
    d.close()

    6.15 xml模块

    xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,在json还没诞生的黑暗年代,只能选择用xml,至今很多传统公司如金融行业的很多系统的接口还主要是xml

    6.151 xml模块举例:

    <data>
        <country name="Liechtenstein">
            <rank updated="yes">2</rank>
            <year updated="yes">2018</year>
            <neighbor direction="E" name="Austria" />
            <neighbor direction="W" name="Switzerland" />
        </country>
        <country name="Singapore">
            <rank updated="yes">5</rank>
            <year updated="yes">2021</year>
            <neighbor direction="N" name="Malaysia" />
        </country>
        <country name="Panama">
            <rank updated="yes">69</rank>
            <year updated="yes">2021</year>
            <neighbor direction="W" name="Costa Rica" />
            <neighbor direction="E" name="Colombia" />
        </country>
    </data>

    查 : 三种查找节点的方式

    import xml.etree.ElementTree as ET
    tree=ET.parse('a.xml')
    root=tree.getroot()
    ​
    res=root.iter('rank')       # 会在整个树中进行查找,而且是查找到所有
    for item in res:           
        print(item)             # <Element     'rank' at 0x000002C3C109A9F8>.....
        print(item.tag)         # 标签名       rank  rank  rank
        print(item.attrib)      # 属性        {'updated': 'yes'}  {'updated': 'yes'}... 
        print(item.text)        # 文本内容     2  5  69
    ​
    res=root.find('country')    # 只能在当前元素的下一级开始查找。并且只找到一个就结束
    print(res.tag)
    print(res.attrib)
    print(res.text)
    nh=res.find('neighbor')      # 在res的下一级查找
    print(nh.tag)
    print(nh.attrib)
    ​
    cy=root.findall('country')   # 只能在当前元素的下一级开始查找, 但是查找到所有
    print([item.attrib for item in cy]) #[{'name':'Liechtenstein'},{'name':'Singapore'},{'name':'Panama'}]

    改:

    import xml.etree.ElementTree as ET
    tree=ET.parse('a.xml')
    root=tree.getroot()
    ​
    res=root.iter('year') 
    for item in res:
        item.text=str(int(item.text) + 10)
        item.attrib={'updated':'yes'}
    ​
    tree.write('a.xml')                     #把更改写入
    tree.write('c.xml')                     #新建一个.xml文件,把更改的结果写入

    增:

    import xml.etree.ElementTree as ET
    tree=ET.parse('a.xml')
    root=tree.getroot()
    ​
    for country in root.iter('country'):
        year=country.find('year')
        if int(year.text) > 2020:
            ele=ET.Element('egon')
            ele.attrib={'nb':'yes'}
            ele.text='非常帅'
            country.append(ele)
            country.remove(year)
            
    tree.write('b.xml')
  • 相关阅读:
    Leetcode Spiral Matrix
    Leetcode Sqrt(x)
    Leetcode Pow(x,n)
    Leetcode Rotate Image
    Leetcode Multiply Strings
    Leetcode Length of Last Word
    Topcoder SRM 626 DIV2 SumOfPower
    Topcoder SRM 626 DIV2 FixedDiceGameDiv2
    Leetcode Largest Rectangle in Histogram
    Leetcode Set Matrix Zeroes
  • 原文地址:https://www.cnblogs.com/mylu/p/11086966.html
Copyright © 2011-2022 走看看