python 一些基本库 II

python 一些基本库 II


1 输出格式 reprlib, pprint, textwrap, locate

    
  1  reprlib  # reprlib模块提供了repr()的一个版本,定制大的或者多层嵌套的容器的简洁展示
  
        import reprlib
        >>> reprlib.repr(set('supercalifragilisticexpialidocious'))
        "{'a', 'c', 'd', 'e', 'f', 'g', ...}"
  
  2  pprint  # pprint模块为打印内建的和用户自定义的对象上提供了更复杂的控制,当结果超过了一行,“美化打印”增加了分行机制以更清晰的展示数据结构

          import pprint
        
          t = []
        
          t = [[[1,2],3,4],5,6]
        
          pprint.pprint(t,width=3)
        [[[1,
           2],
          3,
          4],
         5,
         6]
         
  3  textwrap  # 模块格式化文章的段落以适应屏幕宽度
  
  
  
In [35]: doc = """The wrap() method is just like fill() except that it returns
    ...:     a list of strings instead of one big string with newlines to separate
    ...:     the wrapped lines."""
    ...:

    import textwrap
   
    print(textwrap.fill(doc, width=20))
    
        just like fill()
        except that it
        returns     a list
        of strings instead
        of one big string
        The wrap() method is
        with newlines to
        separate     the
        wrapped lines.


2 模板替换 string.Templating




    >>> from string import Template
    
    >>> t = Template('${village}folk send $$10 to $cause.')
    >>> t.substitute(village='Nottingham', cause='the ditch fund')
    
    'Nottinghamfolk send $10 to the ditch fund.'


    
    >>> import time, os.path
    
    >>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
    
    
    >>> class BatchRename(Template):
    ...     delimiter = '%'
    
    
    >>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format):  ')
    
                Enter rename style (%d-date %n-seqnum %f-format):  Ashley_%n%f
    
    >>> t = BatchRename(fmt)
    >>> date = time.strftime('%d%b%y')
    
    >>> for i, filename in enumerate(photofiles):
    ...     base, ext = os.path.splitext(filename)
    ...     newname = t.substitute(d=date, n=i, f=ext)
    ...     print('{0} --> {1}'.format(filename, newname))
    
        
        img_1074.jpg --> Ashley_0.jpg
        img_1076.jpg --> Ashley_1.jpg
        img_1077.jpg --> Ashley_2.jpg
    


3 二进制处理(binary)struct


    
    import struct
    
    with open('myfile.zip', 'rb') as f:
        data = f.read()
    
    start = 0
    for i in range(3):                      # show the first 3 file headers
        start += 14
        fields = struct.unpack('<IIIHH', data[start:start+16])
        crc32, comp_size, uncomp_size, filenamesize, extra_size = fields
    
        start += 16
        filename = data[start:start+filenamesize]
        start += filenamesize
        extra = data[start:start+extra_size]
        print(filename, hex(crc32), comp_size, uncomp_size)
    
        start += extra_size + comp_size     # skip to the next header
    


4 弱引用 weakref

1. 如果循环引用的话需要使用弱引用,便于系统的垃圾回收.
2. proxy和ref创建的弱引用区别,如果被引用对象被删除,ref会返回None,而proxy则会报错:weakref.ReferenceError

    >>> import weakref, gc
    >>> class A:
    ...     def __init__(self, value):
    ...         self.value = value
    ...     def __repr__(self):
    ...         return str(self.value)
    ...
    >>> a = A(10)                   # create a reference
    >>> d = weakref.WeakValueDictionary()
    >>> d['primary'] = a            # does not create a reference
    >>> d['primary']                # fetch the object if it is still alive
    10
    >>> del a                       # removgite the one reference
    >>> gc.collect()                # run garbage collection right away
    0
    >>> d['primary']                # entry was automatically removed
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
        d['primary']                # entry was automatically removed
      File "C:/python37/lib/weakref.py", line 46, in __getitem__
        o = self.data[key]()
    KeyError: 'primary'
Buy me a 肥仔水!