zoukankan      html  css  js  c++  java
  • python3 小技巧(2)

    原文 http://blog.csdn.net/jclass/article/details/6145078

    一. base64 编码和解码任意的二进制字符串到文本字符串(主要用在HTTP EMAIL URL等 )
    官方帮助文档原文:This module provides data encoding and decoding as specified in RFC 3548.
    This standard defines the Base16, Base32, and Base64 algorithms for encoding and decoding arbitrary binary strings
    into text strings that can be safely sent by email, used as parts of URLs, or included as part of an HTTP POST request

    >>> import base64  
    >>> base64.encode(open("D:/xda1.txt","rb"),open("D:/text2.txt","wb")) #将xda1.txt文件编码并保存到text2.txt
    >>> base64.decode(open("D:/text2.txt","rb"),open("D:/text3.txt","wb"))#将text2.txt文件解码并保存到xda1.txt
    >>> mm = base64.encodestring(b"mima ")
    >>> mm
    b'bWltYSA=/n'
    >>> dd = base64.decodebytes(mm)
    >>> dd
    b'mima '
    >>> base64.b64encode(b"mima ")
    b'bWltYSA='
    >>> base64.b64decode(mm)
    b'mima '


     

    二. 3.1中marshal与pickle都能存取compile的Code对象
    官方文档中不建议使用marshal:This is not a general “persistence” module.

    >>> s = """ 
    print('hello')
    """
    >>> exec(compile(s,"","exec")) #直接执行
    hello
    >>> import marshal #marshal存取
    >>> data = marshal.dumps(compile(s,"","exec"))
    >>> repr(data)
    "b'c//x00//x00//x00//x00//x00//x00//x00//x00//x00//x00//x00//x00//x02//x00//x00//x00@//x00//x00//x00s//x0e//x00//x00//x00e//x00//x00d//x00//x00//x83//x01//x00//x01d//x01//x00S(//x02//x00//x00//x00u//x05//x00//x00//x00helloN(//x01//x00//x00//x00u//x05//x00//x00//x00print(//x00//x00//x00//x00(//x00//x00//x00//x00(//x00//x00//x00//x00u//x00//x00//x00//x00u//x08//x00//x00//x00<module>//x02//x00//x00//x00s//x00//x00//x00//x00'"
    >>> exec(marshal.loads(data))
    hello
    >>> import pickle #pikle存取 调用都一样
    >>> data1 = pickle.dumps(compile(s,"","exec"))
    >>> data1
    b'/x80/x03cidlelib.rpc/nunpickle_code/nq/x00Cqc/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x02/x00/x00/x00@/x00/x00/x00s/x0e/x00/x00/x00e/x00/x00d/x00/x00/x83/x01/x00/x01d/x01/x00S(/x02/x00/x00/x00u/x05/x00/x00/x00helloN(/x01/x00/x00/x00u/x05/x00/x00/x00print(/x00/x00/x00/x00(/x00/x00/x00/x00(/x00/x00/x00/x00u/x00/x00/x00/x00u/x08/x00/x00/x00<module>/x02/x00/x00/x00s/x00/x00/x00/x00q/x01/x85q/x02Rq/x03.'
    >>> exec(pickle.loads(data1))
    hello
    >>> type(data)
    <class 'bytes'>
    >>> type(data1)
    <class 'bytes'>


     

    三.array操作


    >>> from array import array
    >>> array('u','abcdazx') #字符串
    array('u', 'abcdazx')
    >>> a.append('c') #注意:只能一次添加一个字符
    >>> a.tolist() #将array转换为一样项的普通列表('u'转成字符串列表,'b'转成数字列表)
    ['a', 'b', 'c', 'd', 'a', 'z', 'x', 'c']
    >>> a.tounicode()#将array转换为字符串
    'abcdazxc'
    >>> a.tostring() #输出字节的串
    b'a/x00b/x00c/x00d/x00a/x00z/x00x/x00c/x00'
    >>> b= array('b',b'abcdazx')#字节的串
    >>> b
    array('b', [97, 98, 99, 100, 97, 122, 120])
    >>> b = array('b',b'z') #单个字节
    >>> b
    array('b', [122])#ASCII编码值
    >>> b.tostring() #将ASCII编码值还原为原始值
    b'z'
    >>> array('i',[1]).tostring() #整数
    b'/x01/x00/x00/x00'
    >>> array('i',[1]).tostring()[0]
    1
    >>> array('i',[1]).tostring()[1]
    0


     

    四. py_compile编译单个py文件为pyc字节码文件
    如果不指定保存的文件(compile第二参数),则将编译好的字节代码文件保存到py同一目录。
    compileall 模块使用compileall.compile_dir()可以把一个目录树下的所有 Python 文件编译为字节代码.

    >>> import py_compile  
    >>> py_compile.compile("E:/Python/ProjecQt/test.py") #生成test.pyc文件



    五. linecache从源文件中读取代码(并缓存)

    >>> import linecache  
    >>> #test.py 只有一行代码情况:print("aa")
    >>> print(linecache.getline("E:/Python/ProjecQt/test.py",1)) #参数1代表读取的第一行
    print("aa")
    >>> print(linecache.getline("E:/Python/ProjecQt/test.py",2)) #由于第二没有代码,则输出空行

    >>> #test.py 两行代码情况:print("bb") print("a")
    >>> print(linecache.getline("E:/Python/ProjecQt/test.py",1)) #由于缓存了行代码,则输出仍旧是原始的行
    print("aa")
    >>> linecache.clearcache() #清除缓存
    >>> print(linecache.getline("E:/Python/ProjecQt/test.py",1))
    print("bb")

    >>> print(linecache.getline("E:/Python/ProjecQt/test.py",2))
    print("aa")


     

    六. calendar查看日历

    calendar.Calendar():查询日历的类(无格式化)
    calendar.TextCalendar():取得文本日历字符串(可格式化)
    calendar.HTMLCalendar():取得HTML日历字节的串(可格式化)

    >>> import calendar  
    >>> calendar.prmonth(1999,12) #打印某年某月的日期,如果要返回字符串可使用calendar.month()
    December 1999
    Mo Tu We Th Fr Sa Su
    1 2 3 4 5
    6 7 8 9 10 11 12
    13 14 15 16 17 18 19
    20 21 22 23 24 25 26
    27 28 29 30 31

    >>> calendar.prcal(2011) #打印整年的日历,返回字符串使用calendar.calendar()
    2011

    January February March
    Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
    1 2 1 2 3 4 5 6 1 2 3 4 5 6
    3 4 5 6 7 8 9 7 8 9 10 11 12 13 7 8 9 10 11 12 13
    10 11 12 13 14 15 16 14 15 16 17 18 19 20 14 15 16 17 18 19 20
    17 18 19 20 21 22 23 21 22 23 24 25 26 27 21 22 23 24 25 26 27
    24 25 26 27 28 29 30 28 28 29 30 31
    31

    April May June
    Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
    1 2 3 1 1 2 3 4 5
    4 5 6 7 8 9 10 2 3 4 5 6 7 8 6 7 8 9 10 11 12
    11 12 13 14 15 16 17 9 10 11 12 13 14 15 13 14 15 16 17 18 19
    18 19 20 21 22 23 24 16 17 18 19 20 21 22 20 21 22 23 24 25 26
    25 26 27 28 29 30 23 24 25 26 27 28 29 27 28 29 30
    30 31

    July August September
    Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
    1 2 3 1 2 3 4 5 6 7 1 2 3 4
    4 5 6 7 8 9 10 8 9 10 11 12 13 14 5 6 7 8 9 10 11
    11 12 13 14 15 16 17 15 16 17 18 19 20 21 12 13 14 15 16 17 18
    18 19 20 21 22 23 24 22 23 24 25 26 27 28 19 20 21 22 23 24 25
    25 26 27 28 29 30 31 29 30 31 26 27 28 29 30

    October November December
    Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
    1 2 1 2 3 4 5 6 1 2 3 4
    3 4 5 6 7 8 9 7 8 9 10 11 12 13 5 6 7 8 9 10 11
    10 11 12 13 14 15 16 14 15 16 17 18 19 20 12 13 14 15 16 17 18
    17 18 19 20 21 22 23 21 22 23 24 25 26 27 19 20 21 22 23 24 25
    24 25 26 27 28 29 30 28 29 30 26 27 28 29 30 31
    31

    >>> [i for i in calendar.day_name] #返回当前日历中的天所属的星期
    ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    >>> calendar.isleap(2011) #判断某年是否闰年
    False
    >>> calendar.isleap(2012)
    True
    >>> calendar.leapdays(2000,2020) #返回某年到某年区域中的闰年数
    5
    >>> c = calendar.Calendar()
    >>> c.itermonthdays(2011,1) #某年某月中的天数迭代
    <generator object itermonthdays at 0x014399B8>
    >>> list(c.itermonthdays(2011,2)) #返回某年某月的天数列表
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 0, 0, 0, 0, 0, 0]
    >>> list(c.itermonthdays2(2011,2)) #返回某年某月的天数和星期的元组列表
    [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 0), (8, 1), (9, 2), (10, 3), (11, 4), (12, 5), (13, 6), (14, 0), (15, 1), (16, 2), (17, 3), (18, 4), (19, 5), (20, 6), (21, 0), (22, 1), (23, 2), (24, 3), (25, 4), (26, 5), (27, 6), (28, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6)]
    >>> list(c.itermonthdates(2011,2)) #返回某年某月的datetime.date格式的天数列表
    [datetime.date(2011, 1, 31), datetime.date(2011, 2, 1), datetime.date(2011, 2, 2), datetime.date(2011, 2, 3), datetime.date(2011, 2, 4), datetime.date(2011, 2, 5), datetime.date(2011, 2, 6), datetime.date(2011, 2, 7), datetime.date(2011, 2, 8), datetime.date(2011, 2, 9), datetime.date(2011, 2, 10), datetime.date(2011, 2, 11), datetime.date(2011, 2, 12), datetime.date(2011, 2, 13), datetime.date(2011, 2, 14), datetime.date(2011, 2, 15), datetime.date(2011, 2, 16), datetime.date(2011, 2, 17), datetime.date(2011, 2, 18), datetime.date(2011, 2, 19), datetime.date(2011, 2, 20), datetime.date(2011, 2, 21), datetime.date(2011, 2, 22), datetime.date(2011, 2, 23), datetime.date(2011, 2, 24), datetime.date(2011, 2, 25), datetime.date(2011, 2, 26), datetime.date(2011, 2, 27), datetime.date(2011, 2, 28), datetime.date(2011, 3, 1), datetime.date(2011, 3, 2), datetime.date(2011, 3, 3), datetime.date(2011, 3, 4), datetime.date(2011, 3, 5), datetime.date(2011, 3, 6)]
    >>> ct = calendar.TextCalendar() #生成纯文本日历
    >>> ct.formatmonth(2011,2,3,3) #返回某年某月的格式化的天数,第三个参数(3)代表列宽度为3个空格,第四个参数(3)代表行高度为3个空格
    ' February 2011/n/n/nMon Tue Wed Thu Fri Sat Sun/n/n/n 1 2 3 4 5 6/n/n/n 7 8 9 10 11 12 13/n/n/n 14 15 16 17 18 19 20/n/n/n 21 22 23 24 25 26 27/n/n/n 28/n/n/n'
    >>> strct = ct.formatmonth(2011,2,3,3)
    >>> with open("D:/test.txt","w+") as f:
    f.write(strct) #写入文件


    179

    >>> ''''' test.txt效果如下:
    February 2011


    Mon Tue Wed Thu Fri Sat Sun


    1 2 3 4 5 6


    7 8 9 10 11 12 13


    14 15 16 17 18 19 20


    21 22 23 24 25 26 27


    28


    '''
    >>> ch = calendar.HTMLCalendar() #生成HTML日历
    >>> ch.formatmonth(2011,2)
    '<table border="0" cellpadding="0" cellspacing="0" class="month">/n<tr><th colspan="7" class="month">February 2011</th></tr>/n<tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr>/n<tr><td class="noday"> </td><td class="tue">1</td><td class="wed">2</td><td class="thu">3</td><td class="fri">4</td><td class="sat">5</td><td class="sun">6</td></tr>/n<tr><td class="mon">7</td><td class="tue">8</td><td class="wed">9</td><td class="thu">10</td><td class="fri">11</td><td class="sat">12</td><td class="sun">13</td></tr>/n<tr><td class="mon">14</td><td class="tue">15</td><td class="wed">16</td><td class="thu">17</td><td class="fri">18</td><td class="sat">19</td><td class="sun">20</td></tr>/n<tr><td class="mon">21</td><td class="tue">22</td><td class="wed">23</td><td class="thu">24</td><td class="fri">25</td><td class="sat">26</td><td class="sun">27</td></tr>/n<tr><td class="mon">28</td><td class="noday"> </td><td class="noday"> </td><td class="noday"> </td><td class="noday"> </td><td class="noday"> </td><td class="noday"> </td></tr>/n</table>/n'
    >>> strch = ch.formatmonth(2011,2)
    >>> with open("D:/test.html","w+") as f:
    f.write(strch)


    1198
    >>> ch.formatmonth(2011,2) #返回某年的完整HTML页面字节的串,如何要保存到HTML文件,需进行二进制写操作(带'b'参数)


     

    七. winreg操作注册表

    >>> import winreg  
    >>> explorer = winreg.OpenKey(winreg.HKEY_CURRENT_USER,"Software//Microsoft//Windows//CurrentVersion//Explorer")
    >>> try:
    i = 0
    while True:
    name , value, type = winreg.EnumValue(explorer,i) #返回键下面的所有值的元组对象的枚举(tuple元组分别代表:值名称,值数据,值类型)
    print(name,value,type)
    i += 1
    except WindowsError:#当不存在值时,抛出WindowsError异常。
    print("a WindowsError exception is raised, indicating no more values")


    WebFindBandHook {68F2D3FC-8366-4a46-8224-58EFA2749425} 1
    FileFindBandHook {FFAC7A18-EDF9-40de-BA3F-49FC2269855E} 1
    Link b'/x00/x00/x00/x00' 3
    SearchSystemDirs 1 4
    SearchHidden 1 4
    IncludeSubFolders 1 4
    Logon User Name Administrator 1
    ShellState b'$/x00/x00/x003(/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x01/x00/x00/x00/r/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00' 3
    CleanShutdown 0 4
    Browse For Folder Width 318 4
    Browse For Folder Height 288 4
    FaultCount 0 4
    FaultTime 0 4
    IconUnderline b'/x03/x00/x00/x00' 0
    NoFileFolderConnection 0 4
    CaseSensitive 0 4
    SearchSlowFiles 0 4
    a WindowsError exception is raised, indicating no more values


     

    八. keyword判断是否系统关键字

    >>> import keyword  
    >>> keyword.kwlist
    ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
    >>> keyword.iskeyword("code")
    False
    >>> keyword.iskeyword("None")
    True


     

    九. filecmp比较文件或者目录

    >>> import filecmp  
    >>> filecmp.cmp("d:/xda1.txt","d:/xda1.txt")
    True
    >>> filecmp.cmp("d:/xda1.txt","d:/复件 xda1.txt") #复制一个xda1.txt文件
    True
    >>> filecmp.cmp("d:/xda1.txt","d:/text1.txt") #比较不同内容的文件
    False
    >>> filecmp.cmp("d:/xda1.txt","d:/复件 xda1.txt") #更改复件内容中的数字1为3
    False


     

    十. cmd模块制作自定义命令行操作方式

    cmd 模块为命令行接口( command-line interfaces , CLI )提供了一个简单的框架

    只需要继承 Cmd 类, 定义 do 和 help 方法. 基类会自动地将这些方法转换为对应命令.

    import cmd  
    import string, sys

    class CLI(cmd.Cmd):

    def __init__(self):
    cmd.Cmd.__init__(self)
    self.prompt = '> ' #cmd行头的提示

    def do_hello(self, arg): #do_是执行的方法
    print ("hello again", arg, "!")

    def help_hello(self):#help_是方法的帮助
    print ("syntax: hello [message]"),
    print ("-- prints a hello message")

    def do_quit(self, arg):
    sys.exit(1)

    def help_quit(self):
    print ("syntax: quit"),
    print ("-- terminates the application")

    # shortcuts
    do_q = do_quit #方法调用的快捷方式
    do_h = do_hello

    cli = CLI()
    cli.cmdloop() #一直接受指令

    调用方式:

    >>>   
    > h 123
    hello again 123 !
    > hello 'abc'
    hello again 'abc' !
    > help



    Documented commands (type help <topic>): 
    ======================================== 
    hello  quit 
     
    Undocumented commands: 
    ====================== 
    h  help  q  
      

     

    十一. bisect操作已排序列表

    bisect二叉树计算如何插入已排序的列表,或者返回将插入值在已排序列表中的位置。这种方式比每次比较列表中值执行效率高。

    >>> import bisect  
    >>> aa = [22,55,11,33]
    >>> aa.sort() #排序
    >>> aa
    [11, 22, 33, 55]
    >>> bisect.bisect(aa,99) #bisect_right的别名。返回插入值所在
    4
    >>> bisect.bisect_left(aa,99)
    4
    >>> bisect.bisect(aa,14)
    1
    >>> bisect.bisect_left(aa,14)
    1
    >>> bisect.bisect(aa,22) #插入已经存在的值,则bisect()返回列表中相同值的右边索引
    2
    >>> bisect.bisect_left(aa,22) #插入已经存在的值,则bisect()返回列表中相同值的左边索引
    1
    >>> bisect.insort(aa,12) #向排序列表插入值
    >>> aa
    [11, 12, 22, 33, 55]
    >>> bisect.insort(aa,12) #插入存在的值
    >>> aa
    [11, 12, 12, 22, 33, 55]
    服务项目 技术咨询 微信图书 微信视频 微信代码 定制开发 其他福利
    服务入口 QQ群有问必答
    查看详情
    一本书解决90%问题
    查看详情
    微信开发视频
    小程序开发视频
    免费代码
    ¥1888阿里云代金券
    查看详情
    营销工具
    微信特异功能
  • 相关阅读:
    feedparser win7 python 安装
    Binary Tree Inorder Traversal
    SDUT2013级測试赛_D
    Eclipse中在android项目中出现新建一个Activity后,出现整个project的报错以及包导入以后无法执行等等情况分析。
    代码高亮 highlightjs 使用文档
    android用jsonReader来解析json
    策略模式Strategy——回家乘什么车?
    【转】Android UI系列-----时间、日期、Toasts和进度条Dialog
    【转】24. android dialog ——ProgressDialog 进度条对话框详解
    【转】我的Android笔记(十)—— ProgressDialog的简单应用,等待提示
  • 原文地址:https://www.cnblogs.com/txw1958/p/2364968.html
Copyright © 2011-2022 走看看