Python之常用模块(待更新)

模块,用一砣代码实现了某个功能的代码集合。 

类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py 文件中),n 个 .py 文件组成的代码集合就称为模块。

如:os 是系统相关的模块;file 是文件操作相关的模块

模块分为三种:

  • 自定义模块
  • 内置模块
  • 开源模块

 

自定义模块

 

1、定义模块

情景一:

  

情景二:

  

情景三:

  

2、导入模块

Python 之所以应用越来越广泛,在一定程度上也依赖于其为程序员提供了大量的模块以供使用,如果想要使用模块,则需要导入。导入模块有一下几种方法:

1
2
3
4
import module
from module.xx.xx import xx
from module.xx.xx import xx as rename 
from module.xx.xx import *

导入模块其实就是告诉 Python 解释器去解释那个 py 文件

  • 导入一个 py 文件,解释器解释该 py 文件
  • 导入一个包,解释器解释该包下的 __init__.py 文件

 

开源模块

 

一、下载安装

下载安装有两种方式:

yum 
pip
apt-get
...
方式一
下载源码
解压源码
进入目录
编译源码    python setup.py build
安装源码    python setup.py install
方式二
注:在使用源码安装时,需要使用到 gcc 编译和 python 开发环境,所以,需要先执行:
1
2
3
4
yum install gcc
yum install python-devel
apt-get python-dev

安装成功后,模块会自动安装到 sys.path 中的某个目录中,如:

1
/usr/lib/python2.7/site-packages/

二、导入模块

同自定义模块中导入的方式

三、模块 paramiko

paramiko 是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric 和 ansible 内部的远程管理就是使用的 paramiko 来现实。

1、下载安装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# pycrypto,由于 paramiko 模块内部依赖pycrypto,所以先下载安装pycrypto
  
# 下载安装 pycrypto
wget https://files.cnblogs.com/files/wupeiqi/pycrypto-2.6.1.tar.gz
tar -xvf pycrypto-2.6.1.tar.gz
cd pycrypto-2.6.1
python setup.py build
python setup.py install
  
# 进入python环境,导入Crypto检查是否安装成功
  
# 下载安装 paramiko
wget https://files.cnblogs.com/files/wupeiqi/paramiko-1.10.1.tar.gz
tar -xvf paramiko-1.10.1.tar.gz
cd paramiko-1.10.1
python setup.py build
python setup.py install
  
# 进入python环境,导入paramiko检查是否安装成功

2、使用模块

#!/usr/bin/env python
#coding:utf-8

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(
'192.168.1.108', 22, 'alex', '123')
stdin, stdout, stderr
= ssh.exec_command('df')
print stdout.read()
ssh.close();

执行命令 - 通过用户名和密码连接服务器
import paramiko

private_key_path = '/home/auto/.ssh/id_rsa'
key
= paramiko.RSAKey.from_private_key_file(private_key_path)

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(
'主机名 ', 端口, '用户名', key)

stdin, stdout, stderr = ssh.exec_command('df')
print stdout.read()
ssh.close()

执行命令 - 过密钥链接服务器
import os,sys
import paramiko

t = paramiko.Transport(('182.92.219.86',22))
t.connect(username
='wupeiqi',password='123')
sftp
= paramiko.SFTPClient.from_transport(t)
sftp.put(
'/tmp/test.py','/tmp/test.py')
t.close()

import os,sys
import paramiko

t = paramiko.Transport(('182.92.219.86',22))
t.connect(username
='wupeiqi',password='123')
sftp
= paramiko.SFTPClient.from_transport(t)
sftp.get(
'/tmp/test.py','/tmp/test2.py')
t.close()

上传或者下载文件 - 通过用户名和密码
import paramiko

pravie_key_path = '/home/auto/.ssh/id_rsa'
key
= paramiko.RSAKey.from_private_key_file(pravie_key_path)

t = paramiko.Transport(('182.92.219.86',22))
t.connect(username
='wupeiqi',pkey=key)

sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(
'/tmp/test3.py','/tmp/test3.py')

t.close()

import paramiko

pravie_key_path = '/home/auto/.ssh/id_rsa'
key
= paramiko.RSAKey.from_private_key_file(pravie_key_path)

t = paramiko.Transport(('182.92.219.86',22))
t.connect(username
='wupeiqi',pkey=key)

sftp = paramiko.SFTPClient.from_transport(t)
sftp.get(
'/tmp/test3.py','/tmp/test4.py')

t.close()

上传或下载文件 - 通过密钥

 

内置模块

 

time & datetime 模块

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
32
import time
import datetime
 
time
print(time.clock())  #返回处理器时间,3.3以后废弃 4.444098792316153e-07
print(time.process_time()) #返回处理器时间 0.031200199999999997
print(time.time())     #返回当前系统时间戳 1463472071.3892002
print(time.ctime())    #返回当前系统时间 Tue May 17 16:01:11 2016
print(time.ctime(time.time()-86400))   #转换成字符串格式 Mon May 16 16:01:11 2016
print(time.gmtime(time.time()-86400))  #将时间戳转换成struct_time格式 time.struct_time(tm_year=2016, tm_mon=5, tm_mday=16, tm_hour=8, tm_min=1, tm_sec=11, tm_wday=0, tm_yday=137, tm_isdst=0)
print(time.localtime(time.time()-86400))  #将时间戳转换成struct_time格式,本地时间。 time.struct_time(tm_year=2016, tm_mon=5, tm_mday=16, tm_hour=16, tm_min=13, tm_sec=25, tm_wday=0, tm_yday=137, tm_isdst=0)
print(time.mktime(time.localtime()))  #与time.localtime()功能相反,将struct_time格式转回成时间戳格式  1463472904.0
time.sleep(4) #sleep 每隔四秒以执行
print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将struct_time格式转成指定的字符串格式  2016-05-17 08:16:22
 
datetime
print(datetime.date.today()) #输出格式 2016-05-17
print(datetime.date.fromtimestamp(time.time()-86400) ) # 将时间戳转成日期格式 2016-05-16
current_time = datetime.datetime.now() #
print(current_time) #输出2016-05-17 16:17:59.863200
print(current_time.timetuple()) #返回struct_time格式  time.struct_time(tm_year=2016, tm_mon=5, tm_mday=17, tm_hour=16, tm_min=17, tm_sec=59, tm_wday=1, tm_yday=138, tm_isdst=-1)
 
#datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
print(current_time.replace(2016,5,17)) #输出2016-05-17 16:19:33.753200,返回当前时间,但指定的值将被替换
 
str_to_date = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") #将字符串转换成日期格式
new_date1 = datetime.datetime.now() + datetime.timedelta(days=10) #比现在加10天 2016-05-27 16:21:16.279200
new_date2 = datetime.datetime.now() + datetime.timedelta(days=-10) #比现在减10天 2016-05-07 16:21:44.459200
new_date3 = datetime.datetime.now() + datetime.timedelta(hours=-10) #比现在减10小时 2016-05-17 06:22:01.299200
new_date4 = datetime.datetime.now() + datetime.timedelta(seconds=120) #比现在+120s 2016-05-17 16:24:10.917200
new_date5 = datetime.datetime.now() + datetime.timedelta(weeks=20) #比现在+10周 2016-10-04 16:23:02.904200
print(new_date5)
DirectiveMeaningNotes
%a Locale’s abbreviated weekday name.  
%A Locale’s full weekday name.  
%b Locale’s abbreviated month name.  
%B Locale’s full month name.  
%c Locale’s appropriate date and time representation.  
%d Day of the month as a decimal number [01,31].  
%H Hour (24-hour clock) as a decimal number [00,23].  
%I Hour (12-hour clock) as a decimal number [01,12].  
%j Day of the year as a decimal number [001,366].  
%m Month as a decimal number [01,12].  
%M Minute as a decimal number [00,59].  
%p Locale’s equivalent of either AM or PM. (1)
%S Second as a decimal number [00,61]. (2)
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (3)
%w Weekday as a decimal number [0(Sunday),6].  
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (3)
%x Locale’s appropriate date representation.  
%X Locale’s appropriate time representation.  
%y Year without century as a decimal number [00,99].  
%Y Year with century as a decimal number.  
%z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].  
%Z Time zone name (no characters if no time zone exists).  
%% A literal '%' character.

 

random 模块

随机数

1
2
3
4
mport random
print random.random()
print random.randint(1,2)
print random.randrange(1,10)

生成随机验证码

1
2
3
4
5
6
7
8
9
10
11
import  random
tmp = ""
for i in range(6):
    rad1 = random.randrange(4)
    if rad1 ==1 or rad1 ==3:
        rad2 = random.randrange(0,9)
        tmp += str(rad2)
    else:
        rad3 = random.randrange(65,90)
        tmp += chr(rad3)
print(tmp)

sys 模块

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
import sys
import time
print(sys.argv)    #['C:/Users/Administrator/PycharmProjects/zyl/day-6/datetime,time模块/SYS.PY.py']
 
print(sys.path)    #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
 
print(exit())   #退出程序,正常退出时exit(0)
 
print(sys.version)  #3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]
 
print(sys.maxsize)   #9223372036854775807  最大的Int值
 
print(sys.platform)  #win32       操作系统类型
 
 
####################################安装包流程不换行显示##################################
for  i in range(31):
    sys.stdout.write("\r")         #清空当前数据网上叠加
    sys.stdout.write("%s%% | %s " %(int(i/30*100),int(i/30*100)*"#"))
    sys.stdout.flush()
    time.sleep(0.3)
 
####################################安装流程换行显示####################################
 
for i in range(101):
    sys.stdout.write("\r")
    sys.stdout.write("%s%% | %s \n" %(i,i*"#"))
    sys.stdout.flush()
    time.sleep(0.1)

 

json & pickle 模块

用于序列化的两个模块

  • json,用于字符串 和 python 数据类型间进行转换
  • pickle,用于 python 特有的类型 和 python 的数据类型间进行转换

Json 模块提供了四个功能:dumps、dump、loads、load

pickle 模块提供了四个功能:dumps、dump、loads、load

import pickle

accounts = {
1000: {
'name':'Zhangyanlin',
'email': '75501664@126.com',
'passwd': 'abc123',
'balance': 15000,
'phone': 13651054608,
'bank_acc':{
'ICBC':14324234,
'CBC' : 235234,
'ABC' : 35235423
}
},
1001: {
'name': 'CaiXin Guo',
'email': 'caixin@126.com',
'passwd': 'abc145323',
'balance': -15000,
'phone': 1345635345,
'bank_acc': {
'ICBC': 4334343,
}
},
}

################################ 原始写入文件中去 ###############################
with open("zhang","wb") as f:
f.write(pickle.dumps(accounts))
#打开文件将原数据保存到文件中

################################ 购物环节 #######################################
with open("zhang","rb") as f:
zhang_dic
= pickle.loads(f.read()) #读取出文件里的内容赋值给 zhang_dic 变量

zhang_dic[
1000][<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">balance</span><span style="color: rgba(128, 0, 0, 1)">'</span>] -= 1000 #购物消费 100,总价减去 1000 块钱

with open("zhang","wb") as f:
f.write(pickle.dumps(zhang_dic))
#写入到数据中去

############################## 刷新购物后文件里面的数据 #########################

with open(
"zhang","rb") as f:
shop_old
= pickle.loads(f.read()) #把新数据更新到文件中去
print(shop_old)

pickle 购物实例

 

#json.loads(参数) 将字符串转换成 python 识别的字符
li = '[11,22,33,44,55,66,77,88,99]'
dic = '{"sdkf":"123","askd":"123"}'
print(json.loads(li),type(json.loads(li)))    #列表类型
print(json.loads(dic),type(json.loads(dic)))  #字典类型

#json.dumps(参数) 将 python 字符转换成其他语言识别的字符
li = [11,22,33,44,55]
dic
= {"sdkf":"123","askd":"123"}
print(json.dumps(li),type(json.dumps(li))) #转成字符串
print(json.dumps(dic),type(json.dumps(dic))) #转成字符串

Json 实例

 

 

collection 系列

1、计数器(counter)

Counter 是对字典类型的补充,用于追踪值的出现次数。

ps:具备字典的所有功能 + 自己的功能

1
2
3
c = Counter('abcdeabcdabcaba')
print c
输出:Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
########################################################################
###  Counter
########################################################################

class Counter(dict):
'''Dict subclass for counting hashable items. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values.

&gt;&gt;&gt; c = Counter('abcdeabcdabcaba')  # count elements from a string

&gt;&gt;&gt; c.most_common(3)                # three most common elements
[('a', 5), ('b', 4), ('c', 3)]
&gt;&gt;&gt; sorted(c)                       # list all unique elements
['a', 'b', 'c', 'd', 'e']
&gt;&gt;&gt; ''.join(sorted(c.elements()))   # list elements with repetitions
'aaaaabbbbcccdde'
&gt;&gt;&gt; sum(c.values())                 # total of all counts

&gt;&gt;&gt; c['a']                          # count of letter 'a'
&gt;&gt;&gt; for elem in 'shazam':           # update counts from an iterable
...     c[elem] += 1                # by adding 1 to each element's count
&gt;&gt;&gt; c['a']                          # now there are seven 'a'
&gt;&gt;&gt; del c['b']                      # remove all 'b'
&gt;&gt;&gt; c['b']                          # now there are zero 'b'

&gt;&gt;&gt; d = Counter('simsalabim')       # make another counter
&gt;&gt;&gt; c.update(d)                     # add in the second counter
&gt;&gt;&gt; c['a']                          # now there are nine 'a'

&gt;&gt;&gt; c.clear()                       # empty the counter
&gt;&gt;&gt; c
Counter()

Note:  If a count is set to zero or reduced to zero, it will remain
in the counter until the entry is deleted or the counter is cleared:

&gt;&gt;&gt; c = Counter('aaabbc')
&gt;&gt;&gt; c['b'] -= 2                     # reduce the count of 'b' by two
&gt;&gt;&gt; c.most_common()                 # 'b' is still in, but its count is zero
[('a', 3), ('c', 1), ('b', 0)]

</span><span style="color: rgba(128, 0, 0, 1)">'''</span>
<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> References:</span>
<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">   http://en.wikipedia.org/wiki/Multiset</span>
<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">   http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html</span>
<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">   http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm</span>
<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">   http://code.activestate.com/recipes/259174/</span>
<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">   Knuth, TAOCP Vol. II section 4.6.3</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span>(self, iterable=None, **<span style="color: rgba(0, 0, 0, 1)">kwds):
    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)">Create a new, empty Counter object.  And if given, count elements
    from an input iterable.  Or, initialize the count from another mapping
    of elements to their counts.

    &gt;&gt;&gt; c = Counter()                           # a new, empty counter
    &gt;&gt;&gt; c = Counter('gallahad')                 # a new counter from an iterable
    &gt;&gt;&gt; c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping
    &gt;&gt;&gt; c = Counter(a=4, b=2)                   # a new counter from keyword args

    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(0, 0, 0, 1)">
    super(Counter, self).</span><span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">()
    self.update(iterable, </span>**<span style="color: rgba(0, 0, 0, 1)">kwds)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__missing__</span><span style="color: rgba(0, 0, 0, 1)">(self, key):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> 对于不存在的元素,返回计数器为0 </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">The count of elements not in the Counter is zero.</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Needed so that self[missing_item] does not raise KeyError</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> 0

</span><span style="color: rgba(0, 0, 255, 1)">def</span> most_common(self, n=<span style="color: rgba(0, 0, 0, 1)">None):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> 数量大于等n的所有元素和计数器 </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)">List the n most common elements and their counts from the most
    common to the least.  If n is None, then list all element counts.

    &gt;&gt;&gt; Counter('abcdeabcdabcaba').most_common(3)
    [('a', 5), ('b', 4), ('c', 3)]

    </span><span style="color: rgba(128, 0, 0, 1)">'''</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Emulate Bag.sortedByCount from Smalltalk</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> n <span style="color: rgba(0, 0, 255, 1)">is</span><span style="color: rgba(0, 0, 0, 1)"> None:
        </span><span style="color: rgba(0, 0, 255, 1)">return</span> sorted(self.iteritems(), key=_itemgetter(1), reverse=<span style="color: rgba(0, 0, 0, 1)">True)
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1<span style="color: rgba(0, 0, 0, 1)">))

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> elements(self):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> 计数器中的所有元素,注:此处非所有元素集合,而是包含所有元素集合的迭代器 </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)">Iterator over elements repeating each as many times as its count.

    &gt;&gt;&gt; c = Counter('ABCABC')
    &gt;&gt;&gt; sorted(c.elements())
    ['A', 'A', 'B', 'B', 'C', 'C']

    # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
    &gt;&gt;&gt; prime_factors = Counter({2: 2, 3: 3, 17: 1})
    &gt;&gt;&gt; product = 1
    &gt;&gt;&gt; for factor in prime_factors.elements():     # loop over factors
    ...     product *= factor                       # and multiply them
    &gt;&gt;&gt; product

    Note, if an element's count has been set to zero or is a negative
    number, elements() will ignore it.

    </span><span style="color: rgba(128, 0, 0, 1)">'''</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Emulate Bag.do from Smalltalk and Multiset.begin from C++.</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> _chain.from_iterable(_starmap(_repeat, self.iteritems()))

</span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Override dict methods where necessary</span>
@classmethod def fromkeys(cls, iterable, v=None): # There is no equivalent method for counters because setting v=1 # means that no element can have a count greater than one. raise NotImplementedError( 'Counter.fromkeys()is undefined. Use Counter(iterable) instead.')
</span><span style="color: rgba(0, 0, 255, 1)">def</span> update(self, iterable=None, **<span style="color: rgba(0, 0, 0, 1)">kwds):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> 更新计数器,其实就是增加;如果原来没有,则新建,如果有则加一 </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)">Like dict.update() but add counts instead of replacing them.

    Source can be an iterable, a dictionary, or another Counter instance.

    &gt;&gt;&gt; c = Counter('which')
    &gt;&gt;&gt; c.update('witch')           # add elements from another iterable
    &gt;&gt;&gt; d = Counter('watch')
    &gt;&gt;&gt; c.update(d)                 # add elements from another counter
    &gt;&gt;&gt; c['h']                      # four 'h' in which, witch, and watch

    </span><span style="color: rgba(128, 0, 0, 1)">'''</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> The regular dict.update() operation makes no sense here because the</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> replace behavior results in the some of original untouched counts</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> being mixed-in with all of the other counts for a mismash that</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> doesn't have a straight-forward interpretation in most counting</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> contexts.  Instead, we implement straight-addition.  Both the inputs</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> and outputs are allowed to contain zero and negative counts.</span>

    <span style="color: rgba(0, 0, 255, 1)">if</span> iterable <span style="color: rgba(0, 0, 255, 1)">is</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> None:
        </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> isinstance(iterable, Mapping):
            </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> self:
                self_get </span>=<span style="color: rgba(0, 0, 0, 1)"> self.get
                </span><span style="color: rgba(0, 0, 255, 1)">for</span> elem, count <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> iterable.iteritems():
                    self[elem] </span>= self_get(elem, 0) +<span style="color: rgba(0, 0, 0, 1)"> count
            </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">:
                super(Counter, self).update(iterable) </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> fast path when counter is empty</span>
        <span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">:
            self_get </span>=<span style="color: rgba(0, 0, 0, 1)"> self.get
            </span><span style="color: rgba(0, 0, 255, 1)">for</span> elem <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> iterable:
                self[elem] </span>= self_get(elem, 0) + 1
    <span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> kwds:
        self.update(kwds)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> subtract(self, iterable=None, **<span style="color: rgba(0, 0, 0, 1)">kwds):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> 相减,原来的计数器中的每一个元素的数量减去后添加的元素的数量 </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)">Like dict.update() but subtracts counts instead of replacing them.
    Counts can be reduced below zero.  Both the inputs and outputs are
    allowed to contain zero and negative counts.

    Source can be an iterable, a dictionary, or another Counter instance.

    &gt;&gt;&gt; c = Counter('which')
    &gt;&gt;&gt; c.subtract('witch')             # subtract elements from another iterable
    &gt;&gt;&gt; c.subtract(Counter('watch'))    # subtract elements from another counter
    &gt;&gt;&gt; c['h']                          # 2 in which, minus 1 in witch, minus 1 in watch
    &gt;&gt;&gt; c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch
    -1

    </span><span style="color: rgba(128, 0, 0, 1)">'''</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> iterable <span style="color: rgba(0, 0, 255, 1)">is</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> None:
        self_get </span>=<span style="color: rgba(0, 0, 0, 1)"> self.get
        </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> isinstance(iterable, Mapping):
            </span><span style="color: rgba(0, 0, 255, 1)">for</span> elem, count <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> iterable.items():
                self[elem] </span>= self_get(elem, 0) -<span style="color: rgba(0, 0, 0, 1)"> count
        </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">:
            </span><span style="color: rgba(0, 0, 255, 1)">for</span> elem <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> iterable:
                self[elem] </span>= self_get(elem, 0) - 1
    <span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> kwds:
        self.subtract(kwds)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> copy(self):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> 拷贝 </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">Return a shallow copy.</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span> self.<span style="color: rgba(128, 0, 128, 1)">__class__</span><span style="color: rgba(0, 0, 0, 1)">(self)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__reduce__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> 返回一个元组(类型,元组) </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span> self.<span style="color: rgba(128, 0, 128, 1)">__class__</span><span style="color: rgba(0, 0, 0, 1)">, (dict(self),)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__delitem__</span><span style="color: rgba(0, 0, 0, 1)">(self, elem):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> 删除元素 </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">Like dict.__delitem__() but does not raise KeyError for missing values.</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> elem <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> self:
        super(Counter, self).</span><span style="color: rgba(128, 0, 128, 1)">__delitem__</span><span style="color: rgba(0, 0, 0, 1)">(elem)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__repr__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> self:
        </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">%s()</span><span style="color: rgba(128, 0, 0, 1)">'</span> % self.<span style="color: rgba(128, 0, 128, 1)">__class__</span>.<span style="color: rgba(128, 0, 128, 1)">__name__</span><span style="color: rgba(0, 0, 0, 1)">
    items </span>= <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">, </span><span style="color: rgba(128, 0, 0, 1)">'</span>.join(map(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">%r: %r</span><span style="color: rgba(128, 0, 0, 1)">'</span>.<span style="color: rgba(128, 0, 128, 1)">__mod__</span><span style="color: rgba(0, 0, 0, 1)">, self.most_common()))
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">%s({%s})</span><span style="color: rgba(128, 0, 0, 1)">'</span> % (self.<span style="color: rgba(128, 0, 128, 1)">__class__</span>.<span style="color: rgba(128, 0, 128, 1)">__name__</span><span style="color: rgba(0, 0, 0, 1)">, items)

</span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Multiset-style mathematical operations discussed in:</span>
<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">       Knuth TAOCP Volume II section 4.6.3 exercise 19</span>
<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">       and at http://en.wikipedia.org/wiki/Multiset</span>
<span style="color: rgba(0, 128, 0, 1)">#

# Outputs guaranteed to only include positive counts.
#
# To strip negative and zero counts, add-in an empty counter:
# c += Counter()

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__add__</span><span style="color: rgba(0, 0, 0, 1)">(self, other):
    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)">Add counts from two counters.

    &gt;&gt;&gt; Counter('abbb') + Counter('bcc')
    Counter({'b': 4, 'c': 2, 'a': 1})

    </span><span style="color: rgba(128, 0, 0, 1)">'''</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> isinstance(other, Counter):
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> NotImplemented
    result </span>=<span style="color: rgba(0, 0, 0, 1)"> Counter()
    </span><span style="color: rgba(0, 0, 255, 1)">for</span> elem, count <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> self.items():
        newcount </span>= count +<span style="color: rgba(0, 0, 0, 1)"> other[elem]
        </span><span style="color: rgba(0, 0, 255, 1)">if</span> newcount &gt;<span style="color: rgba(0, 0, 0, 1)"> 0:
            result[elem] </span>=<span style="color: rgba(0, 0, 0, 1)"> newcount
    </span><span style="color: rgba(0, 0, 255, 1)">for</span> elem, count <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> other.items():
        </span><span style="color: rgba(0, 0, 255, 1)">if</span> elem <span style="color: rgba(0, 0, 255, 1)">not</span> <span style="color: rgba(0, 0, 255, 1)">in</span> self <span style="color: rgba(0, 0, 255, 1)">and</span> count &gt;<span style="color: rgba(0, 0, 0, 1)"> 0:
            result[elem] </span>=<span style="color: rgba(0, 0, 0, 1)"> count
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> result

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__sub__</span><span style="color: rgba(0, 0, 0, 1)">(self, other):
    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)"> Subtract count, but keep only results with positive counts.

    &gt;&gt;&gt; Counter('abbbc') - Counter('bccd')
    Counter({'b': 2, 'a': 1})

    </span><span style="color: rgba(128, 0, 0, 1)">'''</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> isinstance(other, Counter):
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> NotImplemented
    result </span>=<span style="color: rgba(0, 0, 0, 1)"> Counter()
    </span><span style="color: rgba(0, 0, 255, 1)">for</span> elem, count <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> self.items():
        newcount </span>= count -<span style="color: rgba(0, 0, 0, 1)"> other[elem]
        </span><span style="color: rgba(0, 0, 255, 1)">if</span> newcount &gt;<span style="color: rgba(0, 0, 0, 1)"> 0:
            result[elem] </span>=<span style="color: rgba(0, 0, 0, 1)"> newcount
    </span><span style="color: rgba(0, 0, 255, 1)">for</span> elem, count <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> other.items():
        </span><span style="color: rgba(0, 0, 255, 1)">if</span> elem <span style="color: rgba(0, 0, 255, 1)">not</span> <span style="color: rgba(0, 0, 255, 1)">in</span> self <span style="color: rgba(0, 0, 255, 1)">and</span> count &lt;<span style="color: rgba(0, 0, 0, 1)"> 0:
            result[elem] </span>= 0 -<span style="color: rgba(0, 0, 0, 1)"> count
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> result

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__or__</span><span style="color: rgba(0, 0, 0, 1)">(self, other):
    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)">Union is the maximum of value in either of the input counters.

    &gt;&gt;&gt; Counter('abbb') | Counter('bcc')
    Counter({'b': 3, 'c': 2, 'a': 1})

    </span><span style="color: rgba(128, 0, 0, 1)">'''</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> isinstance(other, Counter):
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> NotImplemented
    result </span>=<span style="color: rgba(0, 0, 0, 1)"> Counter()
    </span><span style="color: rgba(0, 0, 255, 1)">for</span> elem, count <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> self.items():
        other_count </span>=<span style="color: rgba(0, 0, 0, 1)"> other[elem]
        newcount </span>= other_count <span style="color: rgba(0, 0, 255, 1)">if</span> count &lt; other_count <span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> count
        </span><span style="color: rgba(0, 0, 255, 1)">if</span> newcount &gt;<span style="color: rgba(0, 0, 0, 1)"> 0:
            result[elem] </span>=<span style="color: rgba(0, 0, 0, 1)"> newcount
    </span><span style="color: rgba(0, 0, 255, 1)">for</span> elem, count <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> other.items():
        </span><span style="color: rgba(0, 0, 255, 1)">if</span> elem <span style="color: rgba(0, 0, 255, 1)">not</span> <span style="color: rgba(0, 0, 255, 1)">in</span> self <span style="color: rgba(0, 0, 255, 1)">and</span> count &gt;<span style="color: rgba(0, 0, 0, 1)"> 0:
            result[elem] </span>=<span style="color: rgba(0, 0, 0, 1)"> count
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> result

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__and__</span><span style="color: rgba(0, 0, 0, 1)">(self, other):
    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)"> Intersection is the minimum of corresponding counts.

    &gt;&gt;&gt; Counter('abbb') &amp; Counter('bcc')
    Counter({'b': 1})

    </span><span style="color: rgba(128, 0, 0, 1)">'''</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> isinstance(other, Counter):
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> NotImplemented
    result </span>=<span style="color: rgba(0, 0, 0, 1)"> Counter()
    </span><span style="color: rgba(0, 0, 255, 1)">for</span> elem, count <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> self.items():
        other_count </span>=<span style="color: rgba(0, 0, 0, 1)"> other[elem]
        newcount </span>= count <span style="color: rgba(0, 0, 255, 1)">if</span> count &lt; other_count <span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> other_count
        </span><span style="color: rgba(0, 0, 255, 1)">if</span> newcount &gt;<span style="color: rgba(0, 0, 0, 1)"> 0:
            result[elem] </span>=<span style="color: rgba(0, 0, 0, 1)"> newcount
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> result

Counter

collection

 

2、有序字典 (orderedDict)

orderdDict 是对字典类型的补充,他记住了字典元素添加的顺序

class OrderedDict(dict):
    'Dictionary that remembers insertion order'
    # An inherited dict maps keys to values.
    # The inherited dict provides __getitem__, __len__, __contains__, and get.
    # The remaining methods are order-aware.
    # Big-O running times for all methods are the same as regular dictionaries.
<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> The internal self.__map dict maps keys to links in a doubly linked list.</span>
<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> The circular doubly linked list starts and ends with a sentinel element.</span>
<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> The sentinel element never gets deleted (this simplifies the algorithm).</span>
<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Each link is stored as a list of length three:  [PREV, NEXT, KEY].</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span>(self, *args, **<span style="color: rgba(0, 0, 0, 1)">kwds):
    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)">Initialize an ordered dictionary.  The signature is the same as
    regular dictionaries, but keyword arguments are not recommended because
    their insertion order is arbitrary.

    </span><span style="color: rgba(128, 0, 0, 1)">'''</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> len(args) &gt; 1<span style="color: rgba(0, 0, 0, 1)">:
        </span><span style="color: rgba(0, 0, 255, 1)">raise</span> TypeError(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">expected at most 1 arguments, got %d</span><span style="color: rgba(128, 0, 0, 1)">'</span> %<span style="color: rgba(0, 0, 0, 1)"> len(args))
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">:
        self.</span><span style="color: rgba(128, 0, 128, 1)">__root</span>
    <span style="color: rgba(0, 0, 255, 1)">except</span><span style="color: rgba(0, 0, 0, 1)"> AttributeError:
        self.</span><span style="color: rgba(128, 0, 128, 1)">__root</span> = root = []                     <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> sentinel node</span>
        root[:] =<span style="color: rgba(0, 0, 0, 1)"> [root, root, None]
        self.</span><span style="color: rgba(128, 0, 128, 1)">__map</span> =<span style="color: rgba(0, 0, 0, 1)"> {}
    self.</span><span style="color: rgba(128, 0, 128, 1)">__update</span>(*args, **<span style="color: rgba(0, 0, 0, 1)">kwds)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__setitem__</span>(self, key, value, dict_setitem=dict.<span style="color: rgba(128, 0, 128, 1)">__setitem__</span><span style="color: rgba(0, 0, 0, 1)">):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">od.__setitem__(i, y) &lt;==&gt; od[i]=y</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Setting a new item creates a new link at the end of the linked list,</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> and the inherited dictionary is updated with the new key/value pair.</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> key <span style="color: rgba(0, 0, 255, 1)">not</span> <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> self:
        root </span>= self.<span style="color: rgba(128, 0, 128, 1)">__root</span><span style="color: rgba(0, 0, 0, 1)">
        last </span>=<span style="color: rgba(0, 0, 0, 1)"> root[0]
        last[</span>1] = root[0] = self.<span style="color: rgba(128, 0, 128, 1)">__map</span>[key] =<span style="color: rgba(0, 0, 0, 1)"> [last, root, key]
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> dict_setitem(self, key, value)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__delitem__</span>(self, key, dict_delitem=dict.<span style="color: rgba(128, 0, 128, 1)">__delitem__</span><span style="color: rgba(0, 0, 0, 1)">):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">od.__delitem__(y) &lt;==&gt; del od[y]</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Deleting an existing item uses self.__map to find the link which gets</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> removed by updating the links in the predecessor and successor nodes.</span>

dict_delitem(self, key)
link_prev, link_next, _
= self.__map.pop(key)
link_prev[
1] = link_next # update link_prev[NEXT]
link_next[0] = link_prev # update link_next[PREV]

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__iter__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">od.__iter__() &lt;==&gt; iter(od)</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Traverse the linked list in order.</span>
    root = self.<span style="color: rgba(128, 0, 128, 1)">__root</span><span style="color: rgba(0, 0, 0, 1)">
    curr </span>= root[1]                                  <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> start at the first node</span>
    <span style="color: rgba(0, 0, 255, 1)">while</span> curr <span style="color: rgba(0, 0, 255, 1)">is</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> root:
        </span><span style="color: rgba(0, 0, 255, 1)">yield</span> curr[2]                               <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> yield the curr[KEY]</span>
        curr = curr[1]                              <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> move to next node</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__reversed__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">od.__reversed__() &lt;==&gt; reversed(od)</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Traverse the linked list in reverse order.</span>
    root = self.<span style="color: rgba(128, 0, 128, 1)">__root</span><span style="color: rgba(0, 0, 0, 1)">
    curr </span>= root[0]                                  <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> start at the last node</span>
    <span style="color: rgba(0, 0, 255, 1)">while</span> curr <span style="color: rgba(0, 0, 255, 1)">is</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> root:
        </span><span style="color: rgba(0, 0, 255, 1)">yield</span> curr[2]                               <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> yield the curr[KEY]</span>
        curr = curr[0]                              <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> move to previous node</span>

<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> clear(self):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">od.clear() -&gt; None.  Remove all items from od.</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">
    root </span>= self.<span style="color: rgba(128, 0, 128, 1)">__root</span><span style="color: rgba(0, 0, 0, 1)">
    root[:] </span>=<span style="color: rgba(0, 0, 0, 1)"> [root, root, None]
    self.</span><span style="color: rgba(128, 0, 128, 1)">__map</span><span style="color: rgba(0, 0, 0, 1)">.clear()
    dict.clear(self)

</span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> -- the following methods do not depend on the internal structure --</span>

<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> keys(self):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">od.keys() -&gt; list of keys in od</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> list(self)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> values(self):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">od.values() -&gt; list of values in od</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span> [self[key] <span style="color: rgba(0, 0, 255, 1)">for</span> key <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> self]

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> items(self):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">od.items() -&gt; list of (key, value) pairs in od</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span> [(key, self[key]) <span style="color: rgba(0, 0, 255, 1)">for</span> key <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> self]

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> iterkeys(self):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">od.iterkeys() -&gt; an iterator over the keys in od</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> iter(self)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> itervalues(self):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">od.itervalues -&gt; an iterator over the values in od</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 0, 255, 1)">for</span> k <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> self:
        </span><span style="color: rgba(0, 0, 255, 1)">yield</span><span style="color: rgba(0, 0, 0, 1)"> self[k]

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> iteritems(self):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">od.iteritems -&gt; an iterator over the (key, value) pairs in od</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 0, 255, 1)">for</span> k <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> self:
        </span><span style="color: rgba(0, 0, 255, 1)">yield</span><span style="color: rgba(0, 0, 0, 1)"> (k, self[k])

update </span>=<span style="color: rgba(0, 0, 0, 1)"> MutableMapping.update

</span><span style="color: rgba(128, 0, 128, 1)">__update</span> = update <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> let subclasses override update without breaking __init__</span>

<span style="color: rgba(128, 0, 128, 1)">__marker</span> =<span style="color: rgba(0, 0, 0, 1)"> object()

</span><span style="color: rgba(0, 0, 255, 1)">def</span> pop(self, key, default=<span style="color: rgba(128, 0, 128, 1)">__marker</span><span style="color: rgba(0, 0, 0, 1)">):
    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)">od.pop(k[,d]) -&gt; v, remove specified key and return the corresponding
    value.  If key is not found, d is returned if given, otherwise KeyError
    is raised.

    </span><span style="color: rgba(128, 0, 0, 1)">'''</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> key <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> self:
        result </span>=<span style="color: rgba(0, 0, 0, 1)"> self[key]
        </span><span style="color: rgba(0, 0, 255, 1)">del</span><span style="color: rgba(0, 0, 0, 1)"> self[key]
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> result
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> default <span style="color: rgba(0, 0, 255, 1)">is</span> self.<span style="color: rgba(128, 0, 128, 1)">__marker</span><span style="color: rgba(0, 0, 0, 1)">:
        </span><span style="color: rgba(0, 0, 255, 1)">raise</span><span style="color: rgba(0, 0, 0, 1)"> KeyError(key)
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> default

</span><span style="color: rgba(0, 0, 255, 1)">def</span> setdefault(self, key, default=<span style="color: rgba(0, 0, 0, 1)">None):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">od.setdefault(k[,d]) -&gt; od.get(k,d), also set od[k]=d if k not in od</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> key <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> self:
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> self[key]
    self[key] </span>=<span style="color: rgba(0, 0, 0, 1)"> default
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> default

</span><span style="color: rgba(0, 0, 255, 1)">def</span> popitem(self, last=<span style="color: rgba(0, 0, 0, 1)">True):
    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)">od.popitem() -&gt; (k, v), return and remove a (key, value) pair.
    Pairs are returned in LIFO order if last is true or FIFO order if false.

    </span><span style="color: rgba(128, 0, 0, 1)">'''</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> self:
        </span><span style="color: rgba(0, 0, 255, 1)">raise</span> KeyError(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">dictionary is empty</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
    key </span>= next(reversed(self) <span style="color: rgba(0, 0, 255, 1)">if</span> last <span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> iter(self))
    value </span>=<span style="color: rgba(0, 0, 0, 1)"> self.pop(key)
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> key, value

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__repr__</span>(self, _repr_running=<span style="color: rgba(0, 0, 0, 1)">{}):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">od.__repr__() &lt;==&gt; repr(od)</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">
    call_key </span>=<span style="color: rgba(0, 0, 0, 1)"> id(self), _get_ident()
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> call_key <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> _repr_running:
        </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">...</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">
    _repr_running[call_key] </span>= 1
    <span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">:
        </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> self:
            </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">%s()</span><span style="color: rgba(128, 0, 0, 1)">'</span> % (self.<span style="color: rgba(128, 0, 128, 1)">__class__</span>.<span style="color: rgba(128, 0, 128, 1)">__name__</span><span style="color: rgba(0, 0, 0, 1)">,)
        </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">%s(%r)</span><span style="color: rgba(128, 0, 0, 1)">'</span> % (self.<span style="color: rgba(128, 0, 128, 1)">__class__</span>.<span style="color: rgba(128, 0, 128, 1)">__name__</span><span style="color: rgba(0, 0, 0, 1)">, self.items())
    </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)">:
        </span><span style="color: rgba(0, 0, 255, 1)">del</span><span style="color: rgba(0, 0, 0, 1)"> _repr_running[call_key]

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__reduce__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">Return state information for pickling</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">
    items </span>= [[k, self[k]] <span style="color: rgba(0, 0, 255, 1)">for</span> k <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> self]
    inst_dict </span>=<span style="color: rgba(0, 0, 0, 1)"> vars(self).copy()
    </span><span style="color: rgba(0, 0, 255, 1)">for</span> k <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> vars(OrderedDict()):
        inst_dict.pop(k, None)
    </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> inst_dict:
        </span><span style="color: rgba(0, 0, 255, 1)">return</span> (self.<span style="color: rgba(128, 0, 128, 1)">__class__</span><span style="color: rgba(0, 0, 0, 1)">, (items,), inst_dict)
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> self.<span style="color: rgba(128, 0, 128, 1)">__class__</span><span style="color: rgba(0, 0, 0, 1)">, (items,)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> copy(self):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">od.copy() -&gt; a shallow copy of od</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span> self.<span style="color: rgba(128, 0, 128, 1)">__class__</span><span style="color: rgba(0, 0, 0, 1)">(self)

@classmethod
</span><span style="color: rgba(0, 0, 255, 1)">def</span> fromkeys(cls, iterable, value=<span style="color: rgba(0, 0, 0, 1)">None):
    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)">OD.fromkeys(S[, v]) -&gt; New ordered dictionary with keys from S.
    If not specified, the value defaults to None.

    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(0, 0, 0, 1)">
    self </span>=<span style="color: rgba(0, 0, 0, 1)"> cls()
    </span><span style="color: rgba(0, 0, 255, 1)">for</span> key <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> iterable:
        self[key] </span>=<span style="color: rgba(0, 0, 0, 1)"> value
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> self

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__eq__</span><span style="color: rgba(0, 0, 0, 1)">(self, other):
    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)">od.__eq__(y) &lt;==&gt; od==y.  Comparison to another OD is order-sensitive
    while comparison to a regular mapping is order-insensitive.

    </span><span style="color: rgba(128, 0, 0, 1)">'''</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> isinstance(other, OrderedDict):
        </span><span style="color: rgba(0, 0, 255, 1)">return</span> dict.<span style="color: rgba(128, 0, 128, 1)">__eq__</span>(self, other) <span style="color: rgba(0, 0, 255, 1)">and</span><span style="color: rgba(0, 0, 0, 1)"> all(_imap(_eq, self, other))
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> dict.<span style="color: rgba(128, 0, 128, 1)">__eq__</span><span style="color: rgba(0, 0, 0, 1)">(self, other)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__ne__</span><span style="color: rgba(0, 0, 0, 1)">(self, other):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">od.__ne__(y) &lt;==&gt; od!=y</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">not</span> self ==<span style="color: rgba(0, 0, 0, 1)"> other

</span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> -- the following methods support python 3.x style dictionary views --</span>

<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> viewkeys(self):
    </span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">od.viewkeys() -&gt; a set-like object providing a view on od's keys</span><span style="color: rgba(128, 0, 0, 1)">"</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> KeysView(self)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> viewvalues(self):
    </span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">od.viewvalues() -&gt; an object providing a view on od's values</span><span style="color: rgba(128, 0, 0, 1)">"</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> ValuesView(self)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> viewitems(self):
    </span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">od.viewitems() -&gt; a set-like object providing a view on od's items</span><span style="color: rgba(128, 0, 0, 1)">"</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span> ItemsView(self)</pre>
orderedDict

 

3、默认字典 (defaultdict) 

学前需求:

1
2
有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66 , 'k2': 小于66}
values = [11, 22, 33,44,55,66,77,88,99,90]

my_dict = {}

for value in values:
if value>66:
if my_dict.has_key('k1'):
my_dict[
'k1'].append(value)
else:
my_dict[
'k1'] = [value]
else:
if my_dict.has_key('k2'):
my_dict[
'k2'].append(value)
else:
my_dict[
'k2'] = [value]

原生字典
from collections import defaultdict

values = [11, 22, 33,44,55,66,77,88,99,90]

my_dict = defaultdict(list)

for value in values:
if value>66:
my_dict[
'k1'].append(value)
else:
my_dict[
'k2'].append(value)

defaultdict 解决方法

defaultdict 是对字典的类型的补充,他默认给字典的值设置了一个类型。

class defaultdict(dict):
    """
    defaultdict(default_factory[, ...]) --> dict with default factory
The default factory is called without arguments to produce
a new value when a key is not present, in __getitem__ only.
A defaultdict compares equal to a dict with the same items.
All remaining arguments are treated the same as if they were
passed to the dict constructor, including keyword arguments.
</span><span style="color: rgba(128, 0, 0, 1)">"""</span>
<span style="color: rgba(0, 0, 255, 1)">def</span> copy(self): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> D.copy() -&gt; a shallow copy of D. </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__copy__</span>(self, *args, **kwargs): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> D.copy() -&gt; a shallow copy of D. </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__getattribute__</span>(self, name): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> x.__getattribute__('name') &lt;==&gt; x.name </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span>(self, default_factory=None, **kwargs): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> known case of _collections.defaultdict.__init__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">
    defaultdict(default_factory[, ...]) --&gt; dict with default factory
    
    The default factory is called without arguments to produce
    a new value when a key is not present, in __getitem__ only.
    A defaultdict compares equal to a dict with the same items.
    All remaining arguments are treated the same as if they were
    passed to the dict constructor, including keyword arguments.
    
    # (copied from class doc)
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__missing__</span>(self, key): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">
    __missing__(key) # Called by __getitem__ for missing key; pseudo-code:
      if self.default_factory is None: raise KeyError((key,))
      self[key] = value = self.default_factory()
      return value
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__reduce__</span>(self, *args, **kwargs): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> Return state information for pickling. </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__repr__</span>(self): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> x.__repr__() &lt;==&gt; repr(x) </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span><span style="color: rgba(0, 0, 0, 1)">

default_factory </span>= property(<span style="color: rgba(0, 0, 255, 1)">lambda</span> self: object(), <span style="color: rgba(0, 0, 255, 1)">lambda</span> self, v: None, <span style="color: rgba(0, 0, 255, 1)">lambda</span> self: None)  <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> default</span>
<span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Factory for default value called by __missing__().</span><span style="color: rgba(128, 0, 0, 1)">"""</span></pre>
defaultdict

4、可命名元组 (namedtuple) 

根据 nametuple 可以创建一个包含 tuple 所有功能以及其他功能的类型。

1
2
3
import collections
  
Mytuple = collections.namedtuple('Mytuple',['x', 'y', 'z'])
class Mytuple(__builtin__.tuple)
 |  Mytuple(x, y)
 |  
 |  Method resolution order:
 |      Mytuple
 |      __builtin__.tuple
 |      __builtin__.object
 |  
 |  Methods defined here:
 |  
 |  __getnewargs__(self)
 |      Return self as a plain tuple.  Used by copy and pickle.
 |  
 |  __getstate__(self)
 |      Exclude the OrderedDict from pickling
 |  
 |  __repr__(self)
 |      Return a nicely formatted representation string
 |  
 |  _asdict(self)
 |      Return a new OrderedDict which maps field names to their values
 |  
 |  _replace(_self, **kwds)
 |      Return a new Mytuple object replacing specified fields with new values
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  _make(cls, iterable, new=<built-in method __new__ of type object>, len=<built-in function len>) from __builtin__.type
 |      Make a new Mytuple object from a sequence or iterable
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(_cls, x, y)
 |      Create new instance of Mytuple(x, y)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      Return a new OrderedDict which maps field names to their values
 |  
 |  x
 |      Alias for field number 0
 |  
 |  y
 |      Alias for field number 1
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  _fields = ('x', 'y')
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from __builtin__.tuple:
 |  
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |  
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x
 |  
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |  
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __getslice__(...)
 |      x.__getslice__(i, j) <==> x[i:j]
 |      
 |      Use of negative indices is not supported.
 |  
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |  
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |  
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |  
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |  
 |  __len__(...)
 |      x.__len__() <==> len(x)
 |  
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |  
 |  __mul__(...)
 |      x.__mul__(n) <==> x*n
 |  
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |  
 |  __rmul__(...)
 |      x.__rmul__(n) <==> n*x
 |  
 |  __sizeof__(...)
 |      T.__sizeof__() -- size of T in memory, in bytes
 |  
 |  count(...)
 |      T.count(value) -> integer -- return number of occurrences of value
 |  
 |  index(...)
 |      T.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.

Mytuple

Mytuple

5、双向队列 (deque)

一个线程安全的双向队列

class deque(object):
    """
    deque([iterable[, maxlen]]) --> deque object
Build an ordered collection with optimized access from its endpoints.
</span><span style="color: rgba(128, 0, 0, 1)">"""</span>
<span style="color: rgba(0, 0, 255, 1)">def</span> append(self, *args, **kwargs): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> Add an element to the right side of the deque. </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> appendleft(self, *args, **kwargs): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> Add an element to the left side of the deque. </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> clear(self, *args, **kwargs): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> Remove all elements from the deque. </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> count(self, value): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> D.count(value) -&gt; integer -- return number of occurrences of value </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> 0

</span><span style="color: rgba(0, 0, 255, 1)">def</span> extend(self, *args, **kwargs): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> Extend the right side of the deque with elements from the iterable </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> extendleft(self, *args, **kwargs): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> Extend the left side of the deque with elements from the iterable </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> pop(self, *args, **kwargs): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> Remove and return the rightmost element. </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> popleft(self, *args, **kwargs): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> Remove and return the leftmost element. </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> remove(self, value): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> D.remove(value) -- remove first occurrence of value. </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> reverse(self): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> D.reverse() -- reverse *IN PLACE* </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> rotate(self, *args, **kwargs): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> Rotate the deque n steps to the right (default n=1).  If n is negative, rotates left. </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__copy__</span>(self, *args, **kwargs): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> Return a shallow copy of a deque. </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__delitem__</span>(self, y): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> x.__delitem__(y) &lt;==&gt; del x[y] </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__eq__</span>(self, y): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> x.__eq__(y) &lt;==&gt; x==y </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__getattribute__</span>(self, name): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> x.__getattribute__('name') &lt;==&gt; x.name </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__getitem__</span>(self, y): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> x.__getitem__(y) &lt;==&gt; x[y] </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__ge__</span>(self, y): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> x.__ge__(y) &lt;==&gt; x&gt;=y </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__gt__</span>(self, y): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> x.__gt__(y) &lt;==&gt; x&gt;y </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__iadd__</span>(self, y): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> x.__iadd__(y) &lt;==&gt; x+=y </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span>(self, iterable=(), maxlen=None): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> known case of _collections.deque.__init__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">
    deque([iterable[, maxlen]]) --&gt; deque object
    
    Build an ordered collection with optimized access from its endpoints.
    # (copied from class doc)
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__iter__</span>(self): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> x.__iter__() &lt;==&gt; iter(x) </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__len__</span>(self): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> x.__len__() &lt;==&gt; len(x) </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__le__</span>(self, y): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> x.__le__(y) &lt;==&gt; x&lt;=y </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__lt__</span>(self, y): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> x.__lt__(y) &lt;==&gt; x&lt;y </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span><span style="color: rgba(0, 0, 0, 1)">

@staticmethod </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> known case of __new__</span>
<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__new__</span>(S, *more): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> T.__new__(S, ...) -&gt; a new object with type S, a subtype of T </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__ne__</span>(self, y): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> x.__ne__(y) &lt;==&gt; x!=y </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__reduce__</span>(self, *args, **kwargs): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> Return state information for pickling. </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__repr__</span>(self): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> x.__repr__() &lt;==&gt; repr(x) </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__reversed__</span>(self): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> D.__reversed__() -- return a reverse iterator over the deque </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__setitem__</span>(self, i, y): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> x.__setitem__(i, y) &lt;==&gt; x[i]=y </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__sizeof__</span>(self): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> real signature unknown; restored from __doc__</span>
    <span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> D.__sizeof__() -- size of D in memory, in bytes </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span><span style="color: rgba(0, 0, 0, 1)">

maxlen </span>= property(<span style="color: rgba(0, 0, 255, 1)">lambda</span> self: object(), <span style="color: rgba(0, 0, 255, 1)">lambda</span> self, v: None, <span style="color: rgba(0, 0, 255, 1)">lambda</span> self: None)  <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> default</span>
<span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">maximum size of a deque or None if unbounded</span><span style="color: rgba(128, 0, 0, 1)">"""</span>


<span style="color: rgba(128, 0, 128, 1)">__hash__</span> = None</pre>
deque

注:既然有双向队列,也有单项队列(先进先出 FIFO )

class Queue:
    """Create a queue object with a given maximum size.
If maxsize is &lt;= 0, the queue size is infinite.
</span><span style="color: rgba(128, 0, 0, 1)">"""</span>
<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span>(self, maxsize=<span style="color: rgba(0, 0, 0, 1)">0):
    self.maxsize </span>=<span style="color: rgba(0, 0, 0, 1)"> maxsize
    self._init(maxsize)
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> mutex must be held whenever the queue is mutating.  All methods</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> that acquire mutex must release it before returning.  mutex</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> is shared between the three conditions, so acquiring and</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> releasing the conditions also acquires and releases mutex.</span>
    self.mutex =<span style="color: rgba(0, 0, 0, 1)"> _threading.Lock()
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Notify not_empty whenever an item is added to the queue; a</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> thread waiting to get is notified then.</span>
    self.not_empty =<span style="color: rgba(0, 0, 0, 1)"> _threading.Condition(self.mutex)
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Notify not_full whenever an item is removed from the queue;</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> a thread waiting to put is notified then.</span>
    self.not_full =<span style="color: rgba(0, 0, 0, 1)"> _threading.Condition(self.mutex)
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Notify all_tasks_done whenever the number of unfinished tasks</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> drops to zero; thread waiting to join() is notified to resume</span>
    self.all_tasks_done =<span style="color: rgba(0, 0, 0, 1)"> _threading.Condition(self.mutex)
    self.unfinished_tasks </span>=<span style="color: rgba(0, 0, 0, 1)"> 0

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> task_done(self):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Indicate that a formerly enqueued task is complete.

    Used by Queue consumer threads.  For each get() used to fetch a task,
    a subsequent call to task_done() tells the queue that the processing
    on the task is complete.

    If a join() is currently blocking, it will resume when all items
    have been processed (meaning that a task_done() call was received
    for every item that had been put() into the queue).

    Raises a ValueError if called more times than there were items
    placed in the queue.
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    self.all_tasks_done.acquire()
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">:
        unfinished </span>= self.unfinished_tasks - 1
        <span style="color: rgba(0, 0, 255, 1)">if</span> unfinished &lt;=<span style="color: rgba(0, 0, 0, 1)"> 0:
            </span><span style="color: rgba(0, 0, 255, 1)">if</span> unfinished &lt;<span style="color: rgba(0, 0, 0, 1)"> 0:
                </span><span style="color: rgba(0, 0, 255, 1)">raise</span> ValueError(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">task_done() called too many times</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
            self.all_tasks_done.notify_all()
        self.unfinished_tasks </span>=<span style="color: rgba(0, 0, 0, 1)"> unfinished
    </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)">:
        self.all_tasks_done.release()

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> join(self):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Blocks until all items in the Queue have been gotten and processed.

    The count of unfinished tasks goes up whenever an item is added to the
    queue. The count goes down whenever a consumer thread calls task_done()
    to indicate the item was retrieved and all work on it is complete.

    When the count of unfinished tasks drops to zero, join() unblocks.
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    self.all_tasks_done.acquire()
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">:
        </span><span style="color: rgba(0, 0, 255, 1)">while</span><span style="color: rgba(0, 0, 0, 1)"> self.unfinished_tasks:
            self.all_tasks_done.wait()
    </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)">:
        self.all_tasks_done.release()

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> qsize(self):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Return the approximate size of the queue (not reliable!).</span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    self.mutex.acquire()
    n </span>=<span style="color: rgba(0, 0, 0, 1)"> self._qsize()
    self.mutex.release()
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> n

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> empty(self):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Return True if the queue is empty, False otherwise (not reliable!).</span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    self.mutex.acquire()
    n </span>= <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> self._qsize()
    self.mutex.release()
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> n

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> full(self):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Return True if the queue is full, False otherwise (not reliable!).</span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    self.mutex.acquire()
    n </span>= 0 &lt; self.maxsize ==<span style="color: rgba(0, 0, 0, 1)"> self._qsize()
    self.mutex.release()
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> n

</span><span style="color: rgba(0, 0, 255, 1)">def</span> put(self, item, block=True, timeout=<span style="color: rgba(0, 0, 0, 1)">None):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Put an item into the queue.

    If optional args 'block' is true and 'timeout' is None (the default),
    block if necessary until a free slot is available. If 'timeout' is
    a non-negative number, it blocks at most 'timeout' seconds and raises
    the Full exception if no free slot was available within that time.
    Otherwise ('block' is false), put an item on the queue if a free slot
    is immediately available, else raise the Full exception ('timeout'
    is ignored in that case).
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    self.not_full.acquire()
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">:
        </span><span style="color: rgba(0, 0, 255, 1)">if</span> self.maxsize &gt;<span style="color: rgba(0, 0, 0, 1)"> 0:
            </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> block:
                </span><span style="color: rgba(0, 0, 255, 1)">if</span> self._qsize() ==<span style="color: rgba(0, 0, 0, 1)"> self.maxsize:
                    </span><span style="color: rgba(0, 0, 255, 1)">raise</span><span style="color: rgba(0, 0, 0, 1)"> Full
            </span><span style="color: rgba(0, 0, 255, 1)">elif</span> timeout <span style="color: rgba(0, 0, 255, 1)">is</span><span style="color: rgba(0, 0, 0, 1)"> None:
                </span><span style="color: rgba(0, 0, 255, 1)">while</span> self._qsize() ==<span style="color: rgba(0, 0, 0, 1)"> self.maxsize:
                    self.not_full.wait()
            </span><span style="color: rgba(0, 0, 255, 1)">elif</span> timeout &lt;<span style="color: rgba(0, 0, 0, 1)"> 0:
                </span><span style="color: rgba(0, 0, 255, 1)">raise</span> ValueError(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">'timeout' must be a non-negative number</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)
            </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">:
                endtime </span>= _time() +<span style="color: rgba(0, 0, 0, 1)"> timeout
                </span><span style="color: rgba(0, 0, 255, 1)">while</span> self._qsize() ==<span style="color: rgba(0, 0, 0, 1)"> self.maxsize:
                    remaining </span>= endtime -<span style="color: rgba(0, 0, 0, 1)"> _time()
                    </span><span style="color: rgba(0, 0, 255, 1)">if</span> remaining &lt;= 0.0<span style="color: rgba(0, 0, 0, 1)">:
                        </span><span style="color: rgba(0, 0, 255, 1)">raise</span><span style="color: rgba(0, 0, 0, 1)"> Full
                    self.not_full.wait(remaining)
        self._put(item)
        self.unfinished_tasks </span>+= 1<span style="color: rgba(0, 0, 0, 1)">
        self.not_empty.notify()
    </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)">:
        self.not_full.release()

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> put_nowait(self, item):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Put an item into the queue without blocking.

    Only enqueue the item if a free slot is immediately available.
    Otherwise raise the Full exception.
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> self.put(item, False)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> get(self, block=True, timeout=<span style="color: rgba(0, 0, 0, 1)">None):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Remove and return an item from the queue.

    If optional args 'block' is true and 'timeout' is None (the default),
    block if necessary until an item is available. If 'timeout' is
    a non-negative number, it blocks at most 'timeout' seconds and raises
    the Empty exception if no item was available within that time.
    Otherwise ('block' is false), return an item if one is immediately
    available, else raise the Empty exception ('timeout' is ignored
    in that case).
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    self.not_empty.acquire()
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">:
        </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> block:
            </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> self._qsize():
                </span><span style="color: rgba(0, 0, 255, 1)">raise</span><span style="color: rgba(0, 0, 0, 1)"> Empty
        </span><span style="color: rgba(0, 0, 255, 1)">elif</span> timeout <span style="color: rgba(0, 0, 255, 1)">is</span><span style="color: rgba(0, 0, 0, 1)"> None:
            </span><span style="color: rgba(0, 0, 255, 1)">while</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> self._qsize():
                self.not_empty.wait()
        </span><span style="color: rgba(0, 0, 255, 1)">elif</span> timeout &lt;<span style="color: rgba(0, 0, 0, 1)"> 0:
            </span><span style="color: rgba(0, 0, 255, 1)">raise</span> ValueError(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">'timeout' must be a non-negative number</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)
        </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">:
            endtime </span>= _time() +<span style="color: rgba(0, 0, 0, 1)"> timeout
            </span><span style="color: rgba(0, 0, 255, 1)">while</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> self._qsize():
                remaining </span>= endtime -<span style="color: rgba(0, 0, 0, 1)"> _time()
                </span><span style="color: rgba(0, 0, 255, 1)">if</span> remaining &lt;= 0.0<span style="color: rgba(0, 0, 0, 1)">:
                    </span><span style="color: rgba(0, 0, 255, 1)">raise</span><span style="color: rgba(0, 0, 0, 1)"> Empty
                self.not_empty.wait(remaining)
        item </span>=<span style="color: rgba(0, 0, 0, 1)"> self._get()
        self.not_full.notify()
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> item
    </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)">:
        self.not_empty.release()

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> get_nowait(self):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Remove and return an item from the queue without blocking.

    Only get an item if one is immediately available. Otherwise
    raise the Empty exception.
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> self.get(False)

</span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Override these methods to implement other queue organizations</span>
<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> (e.g. stack or priority queue).</span>
<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> These will only be called with appropriate locks held</span>

<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Initialize the queue representation</span>
<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> _init(self, maxsize):
    self.queue </span>=<span style="color: rgba(0, 0, 0, 1)"> deque()

</span><span style="color: rgba(0, 0, 255, 1)">def</span> _qsize(self, len=<span style="color: rgba(0, 0, 0, 1)">len):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> len(self.queue)

</span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Put a new item in the queue</span>
<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> _put(self, item):
    self.queue.append(item)

</span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Get an item from the queue</span>
<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> _get(self):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> self.queue.popleft()</pre>
Queue

 

OS 模块

用于提供系统级别的操作:

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
os.getcwd()                 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname")         改变当前脚本工作目录;相当于shell下cd
os.curdir                   返回当前目录: ('.')
os.pardir                   获取当前目录的父目录字符串名:('..')
os.makedirs('dir1/dir2')    可生成多层递归目录
os.removedirs('dirname1')   若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname')         生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname')         删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname')       列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove()                 删除一个文件
os.rename("oldname","new")  重命名文件/目录
os.stat('path/filename')    获取文件/目录信息
os.sep                      操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep                  当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
os.pathsep                  用于分割文件路径的字符串
os.name                     字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command")   运行shell命令,直接显示
os.environ                  获取系统环境变量
os.path.abspath(path)       返回path规范化的绝对路径
os.path.split(path)         将path分割成目录和文件名二元组返回
os.path.dirname(path)       返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path)      返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path)        如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path)         如果path是绝对路径,返回True
os.path.isfile(path)        如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path)         如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path)      返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path)      返回path所指向的文件或者目录的最后修改时间

  

hashlib

用于加密相关的操作,代替了 md5 模块和 sha 模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

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
32
33
34
import hashlib
  
# ######## md5 ########
hash = hashlib.md5()
# help(hash.update)
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
print(hash.digest())
  
  
######## sha1 ########
  
hash = hashlib.sha1()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
  
# ######## sha256 ########
  
hash = hashlib.sha256()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
  
  
# ######## sha384 ########
  
hash = hashlib.sha384()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
  
# ######## sha512 ########
  
hash = hashlib.sha512()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())

以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义 key 再来做加密。

1
2
3
4
5
6
7
import hashlib
  
# ######## md5 ########
  
hash = hashlib.md5(bytes('898oaFs09f',encoding="utf-8"))
hash.update(bytes('admin',encoding="utf-8"))
print(hash.hexdigest())

python 内置还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密

1
2
3
4
5
import hmac
  
h = hmac.new(bytes('898oaFs09f',encoding="utf-8"))
h.update(bytes('admin',encoding="utf-8"))
print(h.hexdigest())
import hashlib

def hash(pwd):
hash
= hashlib.md5(bytes("zhangyanlin",encoding='utf-8'))
hash.update(bytes(pwd,encoding
='utf-8'))
return hash.hexdigest()

def login(username,passwd):
with open(
"db",'r',encoding="utf-8") as f:
for i in f:
i
= i.strip().split("|")
if i[0] == username and i[1] == hash(passwd):
return True

def zc_login(username,passwd):
with open(
"db","a",encoding='utf-8') as f:
use_pwd
= username + "|" + hash(passwd) + "\n"
f.write(use_pwd)
return True

choice = input("1. 登录;2. 注册 \n 请您选择:")
if choice == "1":
for i in range(3):
user
= input("请输入用户名:")
pwd
= input("请输入密码:")
login_1
= login(user,pwd)
if login_1:
print("登录成功")
break
else:
print('登录失败!')
continue
elif choice == "2":
user
= input("请输入用户名:")
pwd
= input("请输入密码:")
login_2
= zc_login(user,pwd)
if login_2:
print("注册成功!")

实例

 

XML

XML 是实现不同语言或程序之间进行数据交换的协议,XML 文件格式如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2023</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria" />
        <neighbor direction="W" name="Switzerland" />
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2026</year>
        <gdppc>59900</gdppc>
        <neighbor direction="N" name="Malaysia" />
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2026</year>
        <gdppc>13600</gdppc>
        <neighbor direction="W" name="Costa Rica" />
        <neighbor direction="E" name="Colombia" />
    </country>
</data>

1、解析 XML

from xml.etree import ElementTree as ET

# 打开文件,读取 XML 内容
str_xml = open('xo.xml', 'r').read()

# 将字符串解析成 xml 特殊对象,root 代指 xml 文件的根节点
root = ET.XML(str_xml)

利用 ElementTree.XML 将字符串解析成 xml 对象
from xml.etree import ElementTree as ET

# 直接解析 xml 文件
tree = ET.parse("xo.xml")

# 获取 xml 文件的根节点
root = tree.getroot()

利用 ElementTree.parse 将文件直接解析成 xml 对象

2、操作 XML

XML 格式类型是节点嵌套节点,对于每一个节点均有以下功能,以便对当前节点进行操作:

class Element:
    """An XML element.
This class is the reference implementation of the Element interface.

An element's length is its number of subelements.  That means if you
want to check if an element is truly empty, you should check BOTH
its length AND its text attribute.

The element tag, attribute names, and attribute values can be either
bytes or strings.

*tag* is the element name.  *attrib* is an optional dictionary containing
element attributes. *extra* are additional element attributes given as
keyword arguments.

Example form:
    &lt;tag attrib&gt;text&lt;child/&gt;...&lt;/tag&gt;tail

</span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">

当前节点的标签名
tag </span>=<span style="color: rgba(0, 0, 0, 1)"> None
</span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">The element's name.</span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">

当前节点的属性

attrib </span>=<span style="color: rgba(0, 0, 0, 1)"> None
</span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Dictionary of the element's attributes.</span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">

当前节点的内容
text </span>=<span style="color: rgba(0, 0, 0, 1)"> None
</span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">
Text before first subelement. This is either a string or the value None.
Note that if there is no text, this attribute may be either
None or the empty string, depending on the parser.

</span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">

tail </span>=<span style="color: rgba(0, 0, 0, 1)"> None
</span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">
Text after this element's end tag, but before the next sibling element's
start tag.  This is either a string or the value None.  Note that if there
was no text, this attribute may be either None or an empty string,
depending on the parser.

</span><span style="color: rgba(128, 0, 0, 1)">"""</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span>(self, tag, attrib={}, **<span style="color: rgba(0, 0, 0, 1)">extra):
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> isinstance(attrib, dict):
        </span><span style="color: rgba(0, 0, 255, 1)">raise</span> TypeError(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">attrib must be dict, not %s</span><span style="color: rgba(128, 0, 0, 1)">"</span> %<span style="color: rgba(0, 0, 0, 1)"> (
            attrib.</span><span style="color: rgba(128, 0, 128, 1)">__class__</span>.<span style="color: rgba(128, 0, 128, 1)">__name__</span><span style="color: rgba(0, 0, 0, 1)">,))
    attrib </span>=<span style="color: rgba(0, 0, 0, 1)"> attrib.copy()
    attrib.update(extra)
    self.tag </span>=<span style="color: rgba(0, 0, 0, 1)"> tag
    self.attrib </span>=<span style="color: rgba(0, 0, 0, 1)"> attrib
    self._children </span>=<span style="color: rgba(0, 0, 0, 1)"> []

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__repr__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">&lt;%s %r at %#x&gt;</span><span style="color: rgba(128, 0, 0, 1)">"</span> % (self.<span style="color: rgba(128, 0, 128, 1)">__class__</span>.<span style="color: rgba(128, 0, 128, 1)">__name__</span><span style="color: rgba(0, 0, 0, 1)">, self.tag, id(self))

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> makeelement(self, tag, attrib):
    创建一个新节点
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Create a new element with the same type.

    *tag* is a string containing the element name.
    *attrib* is a dictionary containing the element attributes.

    Do not call this method, use the SubElement factory function instead.

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span> self.<span style="color: rgba(128, 0, 128, 1)">__class__</span><span style="color: rgba(0, 0, 0, 1)">(tag, attrib)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> copy(self):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Return copy of current element.

    This creates a shallow copy. Subelements will be shared with the
    original tree.

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    elem </span>=<span style="color: rgba(0, 0, 0, 1)"> self.makeelement(self.tag, self.attrib)
    elem.text </span>=<span style="color: rgba(0, 0, 0, 1)"> self.text
    elem.tail </span>=<span style="color: rgba(0, 0, 0, 1)"> self.tail
    elem[:] </span>=<span style="color: rgba(0, 0, 0, 1)"> self
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> elem

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__len__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> len(self._children)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__bool__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    warnings.warn(
        </span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">The behavior of this method will change in future versions.  </span><span style="color: rgba(128, 0, 0, 1)">"</span>
        <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">Use specific 'len(elem)' or 'elem is not None' test instead.</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">,
        FutureWarning, stacklevel</span>=2<span style="color: rgba(0, 0, 0, 1)">
        )
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> len(self._children) != 0 <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> emulate old behaviour, for now</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__getitem__</span><span style="color: rgba(0, 0, 0, 1)">(self, index):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> self._children[index]

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__setitem__</span><span style="color: rgba(0, 0, 0, 1)">(self, index, element):
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> if isinstance(index, slice):</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">     for elt in element:</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">         assert iselement(elt)</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> else:</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">     assert iselement(element)</span>
    self._children[index] =<span style="color: rgba(0, 0, 0, 1)"> element

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__delitem__</span><span style="color: rgba(0, 0, 0, 1)">(self, index):
    </span><span style="color: rgba(0, 0, 255, 1)">del</span><span style="color: rgba(0, 0, 0, 1)"> self._children[index]

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> append(self, subelement):
    为当前节点追加一个子节点
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Add *subelement* to the end of this element.

    The new element will appear in document order after the last existing
    subelement (or directly after the text, if it's the first subelement),
    but before the end tag for this element.

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    self._assert_is_element(subelement)
    self._children.append(subelement)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> extend(self, elements):
    为当前节点扩展 n 个子节点
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Append subelements from a sequence.

    *elements* is a sequence with zero or more elements.

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">for</span> element <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> elements:
        self._assert_is_element(element)
    self._children.extend(elements)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> insert(self, index, subelement):
    在当前节点的子节点中插入某个节点,即:为当前节点创建子节点,然后插入指定位置
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Insert *subelement* at position *index*.</span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    self._assert_is_element(subelement)
    self._children.insert(index, subelement)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> _assert_is_element(self, e):
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Need to refer to the actual Python implementation, not the</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> shadowing C implementation.</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> isinstance(e, _Element_Py):
        </span><span style="color: rgba(0, 0, 255, 1)">raise</span> TypeError(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">expected an Element, not %s</span><span style="color: rgba(128, 0, 0, 1)">'</span> % type(e).<span style="color: rgba(128, 0, 128, 1)">__name__</span><span style="color: rgba(0, 0, 0, 1)">)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> remove(self, subelement):
    在当前节点在子节点中删除某个节点
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Remove matching subelement.

    Unlike the find methods, this method compares elements based on
    identity, NOT ON tag value or contents.  To remove subelements by
    other means, the easiest way is to use a list comprehension to
    select what elements to keep, and then use slice assignment to update
    the parent element.

    ValueError is raised if a matching element could not be found.

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> assert iselement(element)</span>

self._children.remove(subelement)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> getchildren(self):
    获取所有的子节点(废弃)
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">(Deprecated) Return all subelements.

    Elements are returned in document order.

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    warnings.warn(
        </span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">This method will be removed in future versions.  </span><span style="color: rgba(128, 0, 0, 1)">"</span>
        <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">Use 'list(elem)' or iteration over elem instead.</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">,
        DeprecationWarning, stacklevel</span>=2<span style="color: rgba(0, 0, 0, 1)">
        )
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> self._children

</span><span style="color: rgba(0, 0, 255, 1)">def</span> find(self, path, namespaces=<span style="color: rgba(0, 0, 0, 1)">None):
    获取第一个寻找到的子节点
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Find first matching element by tag name or path.

    *path* is a string having either an element tag or an XPath,
    *namespaces* is an optional mapping from namespace prefix to full name.

    Return the first matching element, or None if no element was found.

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> ElementPath.find(self, path, namespaces)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> findtext(self, path, default=None, namespaces=<span style="color: rgba(0, 0, 0, 1)">None):
    获取第一个寻找到的子节点的内容
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Find text for first matching element by tag name or path.

    *path* is a string having either an element tag or an XPath,
    *default* is the value to return if the element was not found,
    *namespaces* is an optional mapping from namespace prefix to full name.

    Return text content of first matching element, or default value if
    none was found.  Note that if an element is found having no text
    content, the empty string is returned.

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> ElementPath.findtext(self, path, default, namespaces)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> findall(self, path, namespaces=<span style="color: rgba(0, 0, 0, 1)">None):
    获取所有的子节点
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Find all matching subelements by tag name or path.

    *path* is a string having either an element tag or an XPath,
    *namespaces* is an optional mapping from namespace prefix to full name.

    Returns list containing all matching elements in document order.

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> ElementPath.findall(self, path, namespaces)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> iterfind(self, path, namespaces=<span style="color: rgba(0, 0, 0, 1)">None):
    获取所有指定的节点,并创建一个迭代器(可以被for循环)
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Find all matching subelements by tag name or path.

    *path* is a string having either an element tag or an XPath,
    *namespaces* is an optional mapping from namespace prefix to full name.

    Return an iterable yielding all matching elements in document order.

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> ElementPath.iterfind(self, path, namespaces)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> clear(self):
    清空节点
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Reset element.

    This function removes all subelements, clears all attributes, and sets
    the text and tail attributes to None.

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    self.attrib.clear()
    self._children </span>=<span style="color: rgba(0, 0, 0, 1)"> []
    self.text </span>= self.tail =<span style="color: rgba(0, 0, 0, 1)"> None

</span><span style="color: rgba(0, 0, 255, 1)">def</span> get(self, key, default=<span style="color: rgba(0, 0, 0, 1)">None):
    获取当前节点的属性值
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Get element attribute.

    Equivalent to attrib.get, but some implementations may handle this a
    bit more efficiently.  *key* is what attribute to look for, and
    *default* is what to return if the attribute was not found.

    Returns a string containing the attribute value, or the default if
    attribute was not found.

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> self.attrib.get(key, default)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> set(self, key, value):
    为当前节点设置属性值
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Set element attribute.

    Equivalent to attrib[key] = value, but some implementations may handle
    this a bit more efficiently.  *key* is what attribute to set, and
    *value* is the attribute value to set it to.

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    self.attrib[key] </span>=<span style="color: rgba(0, 0, 0, 1)"> value

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> keys(self):
    获取当前节点的所有属性的 key

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Get list of attribute names.

    Names are returned in an arbitrary order, just like an ordinary
    Python dict.  Equivalent to attrib.keys()

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> self.attrib.keys()

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> items(self):
    获取当前节点的所有属性值,每个属性都是一个键值对
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Get element attributes as a sequence.

    The attributes are returned in arbitrary order.  Equivalent to
    attrib.items().

    Return a list of (name, value) tuples.

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> self.attrib.items()

</span><span style="color: rgba(0, 0, 255, 1)">def</span> iter(self, tag=<span style="color: rgba(0, 0, 0, 1)">None):
    在当前节点的子孙中根据节点名称寻找所有指定的节点,并返回一个迭代器(可以被for循环)。
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Create tree iterator.

    The iterator loops over the element and all subelements in document
    order, returning all elements with a matching tag.

    If the tree structure is modified during iteration, new or removed
    elements may or may not be included.  To get a stable set, use the
    list() function on the iterator, and loop over the resulting list.

    *tag* is what tags to look for (default is to return all elements)

    Return an iterator containing all the matching elements.

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> tag == <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">*</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">:
        tag </span>=<span style="color: rgba(0, 0, 0, 1)"> None
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> tag <span style="color: rgba(0, 0, 255, 1)">is</span> None <span style="color: rgba(0, 0, 255, 1)">or</span> self.tag ==<span style="color: rgba(0, 0, 0, 1)"> tag:
        </span><span style="color: rgba(0, 0, 255, 1)">yield</span><span style="color: rgba(0, 0, 0, 1)"> self
    </span><span style="color: rgba(0, 0, 255, 1)">for</span> e <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> self._children:
        </span><span style="color: rgba(0, 0, 255, 1)">yield</span> <span style="color: rgba(0, 0, 255, 1)">from</span><span style="color: rgba(0, 0, 0, 1)"> e.iter(tag)

</span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> compatibility</span>
<span style="color: rgba(0, 0, 255, 1)">def</span> getiterator(self, tag=<span style="color: rgba(0, 0, 0, 1)">None):
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Change for a DeprecationWarning in 1.4</span>

warnings.warn(
"This method will be removed in future versions. "
"Use 'elem.iter()' or 'list(elem.iter())' instead.",
PendingDeprecationWarning, stacklevel
=2
)
return list(self.iter(tag))

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> itertext(self):
    在当前节点的子孙中根据节点名称寻找所有指定的节点的内容,并返回一个迭代器(可以被for循环)。
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">Create text iterator.

    The iterator loops over the element and all subelements in document
    order, returning all inner text.

    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    tag </span>=<span style="color: rgba(0, 0, 0, 1)"> self.tag
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span> isinstance(tag, str) <span style="color: rgba(0, 0, 255, 1)">and</span> tag <span style="color: rgba(0, 0, 255, 1)">is</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> None:
        </span><span style="color: rgba(0, 0, 255, 1)">return</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> self.text:
        </span><span style="color: rgba(0, 0, 255, 1)">yield</span><span style="color: rgba(0, 0, 0, 1)"> self.text
    </span><span style="color: rgba(0, 0, 255, 1)">for</span> e <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> self:
        </span><span style="color: rgba(0, 0, 255, 1)">yield</span> <span style="color: rgba(0, 0, 255, 1)">from</span><span style="color: rgba(0, 0, 0, 1)"> e.itertext()
        </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> e.tail:
            </span><span style="color: rgba(0, 0, 255, 1)">yield</span> e.tail</pre>
节点功能一览表

由于 每个节点 都具有以上的方法,并且在上一步骤中解析时均得到了 root(xml 文件的根节点),so   可以利用以上方法进行操作 xml 文件。

a. 遍历 XML 文档的所有内容

from xml.etree import ElementTree as ET

############ 解析方式一 ############
"""

打开文件,读取 XML 内容

str_xml = open('xo.xml', 'r').read()

将字符串解析成 xml 特殊对象,root 代指 xml 文件的根节点

root = ET.XML(str_xml)
"""
############ 解析方式二 ############

# 直接解析 xml 文件
tree = ET.parse("xo.xml")

# 获取 xml 文件的根节点
root = tree.getroot()

### 操作

# 顶层标签
print(root.tag)

# 遍历 XML 文档的第二层
for child in root:
# 第二层节点的标签名称和标签属性
print(child.tag, child.attrib)
# 遍历 XML 文档的第三层
for i in child:
# 第二层节点的标签名称和内容
print(i.tag,i.text)

a

b、遍历 XML 中指定的节点

from xml.etree import ElementTree as ET

############ 解析方式一 ############
"""

打开文件,读取 XML 内容

str_xml = open('xo.xml', 'r').read()

将字符串解析成 xml 特殊对象,root 代指 xml 文件的根节点

root = ET.XML(str_xml)
"""
############ 解析方式二 ############

# 直接解析 xml 文件
tree = ET.parse("xo.xml")

# 获取 xml 文件的根节点
root = tree.getroot()

### 操作

# 顶层标签
print(root.tag)

# 遍历 XML 中所有的 year 节点
for node in root.iter('year'):
# 节点的标签名称和内容
print(node.tag, node.text)

b

c、修改节点内容

由于修改的节点时,均是在内存中进行,其不会影响文件中的内容。所以,如果想要修改,则需要重新将内存中的内容写到文件。

from xml.etree import ElementTree as ET

############ 解析方式一 ############

# 打开文件,读取 XML 内容
str_xml = open('xo.xml', 'r').read()

# 将字符串解析成 xml 特殊对象,root 代指 xml 文件的根节点
root = ET.XML(str_xml)

############ 操作 ############

# 顶层标签
print(root.tag)

# 循环所有的 year 节点
for node in root.iter('year'):
# 将 year 节点中的内容自增一
new_year = int(node.text) + 1
node.text
= str(new_year)

</span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 设置属性</span>
node.set(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">name</span><span style="color: rgba(128, 0, 0, 1)">'</span>, <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">alex</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
node.set(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">age</span><span style="color: rgba(128, 0, 0, 1)">'</span>, <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">18</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 删除属性</span>
<span style="color: rgba(0, 0, 255, 1)">del</span> node.attrib[<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">name</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">]

############ 保存文件 ############
tree = ET.ElementTree(root)
tree.write(
"newnew.xml", encoding='utf-8')

解析字符串方式,修改,保存
from xml.etree import ElementTree as ET

############ 解析方式二 ############

# 直接解析 xml 文件
tree = ET.parse("xo.xml")

# 获取 xml 文件的根节点
root = tree.getroot()

############ 操作 ############

# 顶层标签
print(root.tag)

# 循环所有的 year 节点
for node in root.iter('year'):
# 将 year 节点中的内容自增一
new_year = int(node.text) + 1
node.text
= str(new_year)

</span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 设置属性</span>
node.set(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">name</span><span style="color: rgba(128, 0, 0, 1)">'</span>, <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">alex</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
node.set(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">age</span><span style="color: rgba(128, 0, 0, 1)">'</span>, <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">18</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 删除属性</span>
<span style="color: rgba(0, 0, 255, 1)">del</span> node.attrib[<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">name</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">]

############ 保存文件 ############
tree.write("newnew.xml", encoding='utf-8')

解析文件方式,修改,保存

d、删除节点

from xml.etree import ElementTree as ET

############ 解析字符串方式打开 ############

# 打开文件,读取 XML 内容
str_xml = open('xo.xml', 'r').read()

# 将字符串解析成 xml 特殊对象,root 代指 xml 文件的根节点
root = ET.XML(str_xml)

############ 操作 ############

# 顶层标签
print(root.tag)

# 遍历 data 下的所有 country 节点
for country in root.findall('country'):
# 获取每一个 country 节点下 rank 节点的内容
rank = int(country.find('rank').text)

</span><span style="color: rgba(0, 0, 255, 1)">if</span> rank &gt; 50<span style="color: rgba(0, 0, 0, 1)">:
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 删除指定country节点</span>

root.remove(country)

############ 保存文件 ############
tree = ET.ElementTree(root)
tree.write(
"newnew.xml", encoding='utf-8')

解析字符串方式打开,删除,保存
from xml.etree import ElementTree as ET

############ 解析文件方式 ############

# 直接解析 xml 文件
tree = ET.parse("xo.xml")

# 获取 xml 文件的根节点
root = tree.getroot()

############ 操作 ############

# 顶层标签
print(root.tag)

# 遍历 data 下的所有 country 节点
for country in root.findall('country'):
# 获取每一个 country 节点下 rank 节点的内容
rank = int(country.find('rank').text)

</span><span style="color: rgba(0, 0, 255, 1)">if</span> rank &gt; 50<span style="color: rgba(0, 0, 0, 1)">:
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 删除指定country节点</span>

root.remove(country)

############ 保存文件 ############
tree.write("newnew.xml", encoding='utf-8')

解析文件方式打开,删除,保存

3、创建 XML 文档

from xml.etree import ElementTree as ET

# 创建根节点
root = ET.Element("famliy")

# 创建节点大儿子
son1 = ET.Element('son', {'name': '儿 1'})
# 创建小儿子
son2 = ET.Element('son', {"name": '儿 2'})

# 在大儿子中创建两个孙子
grandson1 = ET.Element('grandson', {'name': '儿 11'})
grandson2
= ET.Element('grandson', {'name': '儿 12'})
son1.append(grandson1)
son1.append(grandson2)

# 把儿子添加到根节点中
root.append(son1)
root.append(son1)

tree = ET.ElementTree(root)
tree.write(
'oooo.xml',encoding='utf-8', short_empty_elements=False)

from xml.etree import ElementTree as ET

# 创建根节点
root = ET.Element("famliy")

# 创建大儿子
#
son1 = ET.Element('son', {'name': '儿 1'})
son1 = root.makeelement('son', {'name': '儿 1'})
# 创建小儿子
#
son2 = ET.Element('son', {"name": '儿 2'})
son2 = root.makeelement('son', {"name": '儿 2'})

# 在大儿子中创建两个孙子
#
grandson1 = ET.Element('grandson', {'name': '儿 11'})
grandson1 = son1.makeelement('grandson', {'name': '儿 11'})
# grandson2 = ET.Element('grandson', {'name': '儿 12'})
grandson2 = son1.makeelement('grandson', {'name': '儿 12'})

son1.append(grandson1)
son1.append(grandson2)

# 把儿子添加到根节点中
root.append(son1)
root.append(son1)

tree = ET.ElementTree(root)
tree.write(
'oooo.xml',encoding='utf-8', short_empty_elements=False)

from xml.etree import ElementTree as ET

# 创建根节点
root = ET.Element("famliy")

# 创建节点大儿子
son1 = ET.SubElement(root, "son", attrib={'name': '儿 1'})
# 创建小儿子
son2 = ET.SubElement(root, "son", attrib={"name": "儿 2"})

# 在大儿子中创建一个孙子
grandson1 = ET.SubElement(son1, "age", attrib={'name': '儿 11'})
grandson1.text
= '孙子'

et = ET.ElementTree(root) #生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True, short_empty_elements=False)

由于原生保存的 XML 时默认无缩进,如果想要设置缩进的话, 需要修改保存方式:

from xml.etree import ElementTree as ET
from xml.dom import minidom

def prettify(elem):
"""将节点转换成字符串,并添加缩进。
"""
rough_string
= ET.tostring(elem, 'utf-8')
reparsed
= minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="\t")

# 创建根节点
root = ET.Element("famliy")

# 创建大儿子
#
son1 = ET.Element('son', {'name': '儿 1'})
son1 = root.makeelement('son', {'name': '儿 1'})
# 创建小儿子
#
son2 = ET.Element('son', {"name": '儿 2'})
son2 = root.makeelement('son', {"name": '儿 2'})

# 在大儿子中创建两个孙子
#
grandson1 = ET.Element('grandson', {'name': '儿 11'})
grandson1 = son1.makeelement('grandson', {'name': '儿 11'})
# grandson2 = ET.Element('grandson', {'name': '儿 12'})
grandson2 = son1.makeelement('grandson', {'name': '儿 12'})

son1.append(grandson1)
son1.append(grandson2)

# 把儿子添加到根节点中
root.append(son1)
root.append(son1)

raw_str = prettify(root)

f = open("xxxoo.xml",'w',encoding='utf-8')
f.write(raw_str)
f.close()

缩进

4、命名空间

from xml.etree import ElementTree as ET

ET.register_namespace('com',"http://www.company.com") #some name

# build a tree structure
root = ET.Element("{http://www.company.com}STUFF")
body
= ET.SubElement(root, "{http://www.company.com}MORE_STUFF", attrib={"{http://www.company.com}hhh": "123"})
body.text
= "STUFF EVERYWHERE!"

# wrap it in an ElementTree instance, and save as XML
tree = ET.ElementTree(root)

tree.write("page.xml",
xml_declaration
=True,
encoding
='utf-8',
method
="xml")

命名

 

requests

 

Python 标准库中提供了:urllib 等模块以供 Http 请求,但是,它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。

import urllib.request

f = urllib.request.urlopen('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508')
result
= f.read().decode('utf-8')

发送 GET 请求
import urllib.request

req = urllib.request.Request('http://www.example.com/')
req.add_header(
'Referer', 'http://www.python.org/')
r
= urllib.request.urlopen(req)

result = f.read().decode('utf-8')

发送携带请求头的 GET 请求

 

Requests 是使用 Apache2 Licensed 许可证的 基于 Python 开发的 HTTP 库,其在 Python 内置模块的基础上进行了高度的封装,从而使得 Pythoner 进行网络请求时,变得美好了许多,使用 Requests 可以轻而易举的完成浏览器可有的任何操作。

1、安装模块

1
pip3 install requests

 

2、使用模块

# 1、无参数实例

import requests

ret = requests.get('https://github.com/timeline.json')

print(ret.url)
print(ret.text)

# 2、有参数实例

import requests

payload = {'key1': 'value1', 'key2': 'value2'}
ret
= requests.get("http://httpbin.org/get", params=payload)

print(ret.url)
print(ret.text)

GET 请求
# 1、基本 POST 实例

import requests

payload = {'key1': 'value1', 'key2': 'value2'}
ret
= requests.post("http://httpbin.org/post", data=payload)

print(ret.text)

# 2、发送请求头和数据实例

import requests
import json

url = 'https://api.github.com/some/endpoint'
payload
= {'some': 'data'}
headers
= {'content-type': 'application/json'}

ret = requests.post(url, data=json.dumps(payload), headers=headers)

print(ret.text)
print(ret.cookies)

POST 请求
requests.get(url, params=None, **kwargs)
requests.post(url, data=None, json=None, **kwargs)
requests.put(url, data=None, **kwargs)
requests.head(url, **kwargs)
requests.delete(url, **kwargs)
requests.patch(url, data=None, **kwargs)
requests.options(url, **kwargs)

# 以上方法均是在此方法的基础上构建
requests.request(method, url, **kwargs)

其他请求

 

3、Http 请求和 XML 实例

实例:检测 QQ 账号是否在线

import urllib
import requests
from xml.etree import ElementTree as ET

# 使用内置模块 urllib 发送 HTTP 请求,或者 XML 格式内容
"""
f = urllib.request.urlopen('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508')
result = f.read().decode('utf-8')
"""

# 使用第三方模块 requests 发送 HTTP 请求,或者 XML 格式内容
r = requests.get('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508')
result
= r.text

# 解析 XML 格式内容
node = ET.XML(result)

# 获取内容
if node.text == "Y":
print("在线")
else:
print("离线")

QQ

实例:查看火车停靠信息

import urllib
import requests
from xml.etree import ElementTree as ET

# 使用内置模块 urllib 发送 HTTP 请求,或者 XML 格式内容
"""
f = urllib.request.urlopen('http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&amp;UserID=')
result = f.read().decode('utf-8')
"""

# 使用第三方模块 requests 发送 HTTP 请求,或者 XML 格式内容
r = requests.get('http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&amp;UserID=')
result
= r.text

# 解析 XML 格式内容
root = ET.XML(result)
for node in root.iter('TrainDetailInfo'):
print(node.find('TrainStation').text,node.find('StartTime').text,node.tag,node.attrib)

火车票

 

综合应用实例

1、通过 HTTP 请求和 XML 实现获取电视节目

     API:http://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx  

#-------------------------------------------- 通过 HTTP 请求和 XML 实现获取电视节目 -------------------------------------

############################ 获得支持的省市(地区)和分类电视列表 DataSet###############################################
import requests
from xml.etree import ElementTree as EL
#
#
f = requests.get("http://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx/getAreaDataSet")
#
relust = f.text

# root = EL.XML(relust)

# for node in root.iter("AreaList"):
#
print(node.find("Area").text)

################################# 获得支持的省市(地区)和分类电视名称 String()########################################

# f = requests.get("http://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx/getAreaString")
#
root = f.text

# relust = EL.XML(root)
#
# print(relust)

# for i in relust:
#
print(i.text)

#################################### 通过电视台 ID 获得该电视台频道列表 DataSet#########################################

# f = requests.get("http://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx/getTVchannelDataSet?theTVstationID=4")

# root = f.text
#
# print(root)

# relust = EL.XML(root)
#
# print(relust)

# for node in relust.iter("TvChanne"):
#
print(node.find("tvChannel").text)

############################### 通过电视台 ID 获得该电视台频道名称 String()###############################################

# f = requests.get("http://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx/getTVchannelString?theTVstationID=4")

# root = f.text

# relust = EL.XML(root)

# for i in relust:
#
print(i.text)

############################### 通过频道 ID 获得该频道节目列表 DataSet###############################################
#
f = requests.get("http://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx/getTVprogramDateSet?theTVchannelID=3&amp;theDate=&amp;userID=")
#
root = f.text

# relust = EL.XML(root)
#
print(relust)

# for node in relust.iter("tvProgramTable"):
#
print("时间:%s 节目:%s 频道:%s" %(node.find('playTime').text,node.find('tvProgram').text,node.find('tvStationInfo').text) )

################################################# 通过频道 ID 获得该频道节目 String()#######################################
#
f = requests.get("http://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx/getTVprogramString?theTVchannelID=2&amp;theDate=&amp;userID=")
#
root = f.text

# relust = EL.XML(root)

# for i in relust:
#
print(i.text)

############################################ 通过省市 ID 或分类电视 ID 获得电视台列表 DataSet################################

# f = requests.get("http://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx/getTVstationDataSet?theAreaID=8")
#
root = f.text

# relust = EL.XML(root)

# for node in relust.iter("TvStation"):
#
print(node.find("tvStationName").text)

########################################## 通过省市 ID 或分类电视 ID 获得电视台名称 String()################################

# f = requests.get("http://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx/getTVstationString?theAreaID=-1")
#
root = f.text

# relust = EL.XML(root)

# for i in relust:
#
print(i.text)

电视节目

2、通过 HTTP 请求和 JSON 实现获取天气状况

     API:http://wthrcdn.etouch.cn/weather_mini?city= 北京

import json,requests

f = requests.get("http://wthrcdn.etouch.cn/weather_mini?city= 北京")
root
= f.text
# print(root,type(root))

new_root = json.loads(root)
print(new_root,type(new_root))

#------------------------------------------------------------------------------------------------------------------
response =requests.get("http://www.weather.com.cn/adat/sk/101010500.html")
response.encoding
= "utf-8"
result
= response.text
print(result,type(result))

new_result = json.loads(result)
print(new_result)

天气预报

 

configparser

configparser 模块用于读取基于 Windows INI 格式的.ini 格式的配置文件。这些文件由命名段祖闯,每个命名段独有自己的变量赋值,格式如下:

# 注释 1
   A comment

[section1] # 节点
k1 = v1 #
k2:v2 #

[section2]
# 节点
k1 = v1 #

格式

configparser 模块往往被忽视,但他是一个及其有用的工具,它可以控制包含极其复杂的用户配置或运行时环境的程序,例如:若编写了必须在大兴框架内运行的组件,那么配置文件往往是提供运行时参数的理想方式

1、获取所有节点

1
2
3
4
5
6
import configparser
  
config = configparser.ConfigParser()
config.read('xxxooo', encoding='utf-8')
ret = config.sections()   #获取大节点
print(ret)

2、获取指定节点下所有的键值对

1
2
3
4
5
6
import configparser
  
config = configparser.ConfigParser()
config.read('xxxooo', encoding='utf-8')
ret = config.items('section1') #键值对
print(ret) 

3、获取指定节点下所有的键

1
2
3
4
5
6
import configparser
  
config = configparser.ConfigParser()
config.read('xxxooo', encoding='utf-8')
ret = config.options('section1')   #二级节点
print(ret)

4、获取指定节点下指定 key 的值

1
2
3
4
5
6
7
8
9
10
import configparser
  
config = configparser.ConfigParser()
config.read('xxxooo', encoding='utf-8')
  
  
v = config.get('section1', 'k1') #获取值的值
# v = config.getint('section1', 'k1')  #整形
# v = config.getfloat('section1', 'k1')   #浮点
# v = config.getboolean('section1', 'k1')   #布尔

5、检查、删除、添加节点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import configparser
  
config = configparser.ConfigParser()
config.read('xxxooo', encoding='utf-8')
  
  
# 检查
has_sec = config.has_section('section1')
print(has_sec)
  
# 添加节点
config.add_section("SEC_1")
config.write(open('xxxooo', 'w'))
  
# 删除节点
config.remove_section("SEC_1")
config.write(open('xxxooo', 'w'))

6、检查、删除、设置指定组内的键值对

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import configparser
  
config = configparser.ConfigParser()
config.read('xxxooo', encoding='utf-8')
  
# 检查
has_opt = config.has_option('section1', 'k1')
print(has_opt)
  
# 删除
config.remove_option('section1', 'k1')
config.write(open('xxxooo', 'w'))
  
# 设置
config.set('section1', 'k10', "123")
config.write(open('xxxooo', 'w'))

 

系统命令 subprocess

 

subprocess 模块包含的函数和对象用于简化创建新进程的任务、控制输入和输出流,以及处理返回代码。此模块的猪獒功能包含在其他各个模块中,如 os、popen、commands

格式

以上执行 shell 命令的相关的模块和函数的功能均在 subprocess 模块中实现,并提供了更丰富的功能。

popen(args,**parms)

以子进程形式执行一个新命令,然后返回代表新进程的 popen 对象,命令在 args 中指定,是字符串(如 “ls -l”)。parms 表示关键字参数的集合,设置这些参数可以控制子进程的各种属性

参数:

    • args:shell 命令,可以是字符串或者序列类型(如:list,元组)
    • bufsize:指定缓冲。0 无缓冲,1 行缓冲, 其他 缓冲区大小, 负值 系统缓冲
    • stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
    • preexec_fn:只在 Unix 平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
    • close_sfs:在 windows 平台下,如果 close_fds 被设置为 True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。
      所以不能将 close_fds 设置为 True 同时重定向子进程的标准输入、输出与错误 (stdin, stdout, stderr)。
    • shell:同上
    • cwd:用于设置子进程的当前目录
    • env:用于指定子进程的环境变量。如果 env = None,子进程的环境变量将从父进程中继承。
    • universal_newlines:不同系统的换行符不同,True -> 同意使用 \n
    • startupinfo 与 createionflags 只在 windows 下有效
      将被传递给底层的 CreateProcess() 函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等 

 

import subprocess
ret1 = subprocess.Popen(["mkdir","t1"])
ret2 = subprocess.Popen("mkdir t2", shell=True)
普通命令

 

终端输入的命令分为两种:

  • 输入即可得到输出,如:ifconfig
  • 输入进行某环境,依赖再输入,如:python

 

 

import subprocess

obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)

View Code

 

import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
obj.stdin.write(
"print(1)\n")
obj.stdin.write(
"print(2)")
obj.stdin.close()

cmd_out = obj.stdout.read()
obj.stdout.close()
cmd_error
= obj.stderr.read()
obj.stderr.close()

print(cmd_out)
print(cmd_error)

View Code
import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
obj.stdin.write(
"print(1)\n")
obj.stdin.write(
"print(2)")

out_error_list = obj.communicate()
print(out_error_list)

View Code
import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
out_error_list
= obj.communicate('print("hello")')
print(out_error_list)

View Code

 

 

call(args,**parms)

此函数与 popen 完全相同,但他指挥简单的执行命令然后返回他的状态代码。如果要执行一个命令,单又不需要捕捉他的输出,可以使用这个函数

执行命令,返回状态码

1
2
ret = subprocess.call(["ls", "-l"], shell=False)
ret = subprocess.call("ls -l", shell=True)

 

check_call(args,**parms)

同 call 函数,但如果退出代码为非 0 值,将引发异常,此异常将退出代码保存在他的 returncode 属性中。

执行命令,如果执行状态码是 0 ,则返回 0,否则抛异常

1
2
subprocess.check_call(["ls", "-l"])
subprocess.check_call("exit 1", shell=True)

 

check_output(args,**parms)

执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常

subprocess.check_output(["echo", "Hello World!"])
subprocess.check_output("exit 1", shell=True)

 

shutil

 

 

高级的 文件、文件夹、压缩包 处理模块

 

shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另一个文件中

1
2
3
import shutil
  
shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))

shutil.copyfile(src, dst)
拷贝文件

1
shutil.copyfile('f1.log', 'f2.log')

shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变

1
shutil.copymode('f1.log', 'f2.log')

shutil.copystat(src, dst)
拷贝状态的信息,包括:mode bits, atime, mtime, flags

1
shutil.copystat('f1.log', 'f2.log')

shutil.copy(src, dst)
拷贝文件和权限

1
2
3
import shutil
  
shutil.copy('f1.log', 'f2.log')

shutil.copy2(src, dst)
拷贝文件和状态信息

1
2
3
import shutil
  
shutil.copy2('f1.log', 'f2.log')

shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件夹

1
2
3
import shutil
  
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
import shutil

shutil.copytree('f1', 'f2', symlinks=True, ignore=shutil.ignore_patterns('.pyc', 'tmp')) #复制除了括号里面的

View Code

shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件

1
2
3
import shutil
  
shutil.rmtree('folder1')

shutil.move(src, dst)
递归的去移动文件,它类似 mv 命令,其实就是重命名。

1
2
3
import shutil
  
shutil.move('folder1', 'folder3')

shutil.make_archive(base_name, format,...)

创建压缩包并返回文件路径,例如:zip、tar

创建压缩包并返回文件路径,例如:zip、tar

    • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
      如:www                        => 保存至当前路径
      如:/Users/wupeiqi/www => 保存至 /Users/wupeiqi/
    • format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
    • root_dir: 要压缩的文件夹路径(默认当前目录)
    • owner: 用户,默认当前用户
    • group: 组,默认当前组
    • logger: 用于记录日志,通常是 logging.Logger 对象
1
2
3
4
5
6
7
8
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
import shutil
ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
   
   
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
import shutil
ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')

shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:

import zipfile

# 压缩
z = zipfile.ZipFile('laxi.zip', 'w')
z.write(
'a.log')
z.write(
'data.data')
z.close()

# 解压
z = zipfile.ZipFile('laxi.zip', 'r')
z.extractall()
z.close()

zip 解压
import tarfile

# 压缩
tar = tarfile.open('your.tar','w')
tar.add(
'/Users/wupeiqi/PycharmProjects/bbs2.log', arcname='bbs2.log')
tar.add(
'/Users/wupeiqi/PycharmProjects/cmdb.log', arcname='cmdb.log')
tar.close()

# 解压
tar = tarfile.open('your.tar','r')
tar.extractall()
# 可设置解压地址
tar.close()

tar 解压