python大神-模块

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

模块分为三种:

  • 自定义模块(本地file.py是文件操作相关的模块)

  • 第三方模块(网站下载)

  • 内置模块 (os 是系统相关的模块)

 安装pip:

wget --no-check-certificate https://bootstrap.pypa.io/ez_setup.py
sudo python ez_setup.py --insecure
wget https://pypi.python.org/packages/11/b6/abcb525026a4be042b486df43905d6893fb04f05aac21c32c638e939e447/pip-9.0.1.tar.gz#md5=35f01da33009719497f01a4ba69d63c9
tar -xf pip-9.0.1.tar.gz
cd pip-8.0.0
sudo python setup.py install
ln -s /usr/local/python27/bin/pip /usr/bin/pip

 

导入模块

  如果想要使用模块,则需要导入。导入模块有一下几种方法?

import module

from module.xx.xx import xx

from module.xx.xx import xx as rename  

from module.xx.xx import *

注:如果是文件夹(abc)里的文件(hgb.py),当要引用文件模块时—— from abc.hgb import *.

 导入模块时是根据sys.path作为基准来进行

import sys
print sys.path

 可以通过 sys.path.append('路径') 添加

import sys
import os
project_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(project_path)
 

内置模块

  一、sys(用于提供对Python解释器相关的操作)

      

 1 sys.argv           命令行参数List,第一个元素是程序本身路径
 2 
 3 sys.exit(n)        退出程序,正常退出时exit(0)
 4 
 5 sys.version        获取Python解释程序的版本信息
 6 
 7 sys.maxint         最大的Int值
 8 
 9 sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
10 
11 sys.platform       返回操作系统平台名称
12 
13 sys.stdin          输入相关
14 
15 sys.stdout         输出相关
16 
17 sys.stderror       错误相关
sys基本知识
 1 import sys
 2 import time
 3 
 4 
 5 def view_bar(num, total):
 6     rate = float(num) / float(total)
 7     rate_num = int(rate * 100)
 8     r = '\r%d%%' % (rate_num, )
 9     sys.stdout.write(r)
10     sys.stdout.flush()
11 
12 
13 if __name__ == '__main__':
14     for i in range(0, 100):
15         time.sleep(0.1)
16         view_bar(i, 100)
17 
18 进度百分比
例子(下载进度条)

  

  二、os(用于提供系统级别的操作)

 1 os.getcwd()                 获取当前工作目录,即当前python脚本工作的目录路径
 2 
 3 os.chdir("dirname")         改变当前脚本工作目录;相当于shell下cd
 4 
 5 os.curdir                   返回当前目录: ('.')
 6 
 7 os.pardir                   获取当前目录的父目录字符串名:('..')
 8 
 9 os.makedirs('dir1/dir2')    可生成多层递归目录
10 
11 os.removedirs('dirname1')   若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
12 
13 os.mkdir('dirname')         生成单级目录;相当于shell中mkdir dirname
14 
15 os.rmdir('dirname')         删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
16 
17 os.listdir('dirname')       列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
18 
19 os.remove()                 删除一个文件
20 
21 os.rename("oldname","new")  重命名文件/目录
22 
23 os.stat('path/filename')    获取文件/目录信息
24 
25 os.sep                      操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
26 
27 os.linesep                  当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
28 
29 os.pathsep                  用于分割文件路径的字符串
30 
31 os.name                     字符串指示当前使用平台。win->'nt'; Linux->'posix'
32 
33 os.system("bash command")   运行shell命令,直接显示
34 
35 os.environ                  获取系统环境变量
36 
37 os.path.abspath(path)       返回path规范化的绝对路径
38 
39 os.path.split(path)         将path分割成目录和文件名二元组返回
40 
41 os.path.dirname(path)       返回path的目录。其实就是os.path.split(path)的第一个元素
42 
43 os.path.basename(path)      返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
44 
45 os.path.exists(path)        如果path存在,返回True;如果path不存在,返回False
46 
47 os.path.isabs(path)         如果path是绝对路径,返回True
48 
49 os.path.isfile(path)        如果path是一个存在的文件,返回True。否则返回False
50 
51 os.path.isdir(path)         如果path是一个存在的目录,则返回True。否则返回False
52 
53 os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
54 
55 os.path.getatime(path)      返回path所指向的文件或者目录的最后存取时间
56 
57 os.path.getmtime(path)      返回path所指向的文件或者目录的最后修改时间
os基本知识

 

  三、hashlib(用于加密相关的操作,代替了2.7版本md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法)

 1 import hashlib
 2 
 3  
 4 
 5 # ######## md5 ########
 6 
 7 hash = hashlib.md5()
 8 
 9 # help(hash.update)
10 
11 hash.update(bytes('admin', encoding='utf-8'))
12 
13 print(hash.hexdigest())
14 
15 print(hash.digest())
16 
17  
18 
19  
20 
21 ######## sha1 ########
22 
23  
24 
25 hash = hashlib.sha1()
26 
27 hash.update(bytes('admin', encoding='utf-8'))
28 
29 print(hash.hexdigest())
30 
31  
32 
33 # ######## sha256 ########
34 
35  
36 
37 hash = hashlib.sha256()
38 
39 hash.update(bytes('admin', encoding='utf-8'))
40 
41 print(hash.hexdigest())
42 
43  
44 
45  
46 
47 # ######## sha384 ########
48 
49  
50 
51 hash = hashlib.sha384()
52 
53 hash.update(bytes('admin', encoding='utf-8'))
54 
55 print(hash.hexdigest())
56 
57  
58 
59 # ######## sha512 ########
60 
61  
62 
63 hash = hashlib.sha512()
64 
65 hash.update(bytes('admin', encoding='utf-8'))
66 
67 print(hash.hexdigest())

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

 

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

 

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

 

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

 

  四、random(随机数的生成)

 1 import random
 2 checkcode = ''
 3 for i in range(4):
 4     current = random.randrange(0,4)
 5     if current != i:
 6         temp = chr(random.randint(65,90))
 7     else:
 8         temp = random.randint(0,9)
 9     checkcode += str(temp)
10 print checkcode
11 
12 随机验证码
验证码

 

  五、re(正则表达式)

 

 1 字符:
 2  
 3  
 4   . 匹配除换行符以外的任意字符
 5   \w 匹配字母或数字或下划线或汉字
 6   \s 匹配任意的空白符
 7   \d 匹配数字
 8   \b 匹配单词的开始或结束
 9   ^ 匹配字符串的开始
10   $ 匹配字符串的结束
11 
12 
13 次数:
14  
15  
16   * 重复零次或更多次
17   + 重复一次或更多次
18   ? 重复零次或一次
19   {n} 重复n次
20   {n,} 重复n次或更多次
21   {n,m} 重复n到m次
re基本字符意义

 

匹陪分为三种:

  • match(从起始位置开始匹配,匹配成功返回一个对象,未匹配成功返回None)_只有开头字符匹配到,才算成功

  • search(search,浏览整个字符串去匹配第一个,未匹配成功返回None)

  • findall(findall,获取非重复的匹配列表;如果有一个组则以列表形式返回,且每一个匹配均是字符串;如果模型中有多个组,则以列表形式返回,且每一个匹配均是元祖;空的匹配也会包含在结果中)

 1 # 无分组
 2         r = re.match("h\w+", origin)
 3         print(r.group())     # 获取匹配到的所有结果
 4         print(r.groups())    # 获取模型中匹配到的分组结果
 5         print(r.groupdict()) # 获取模型中匹配到的分组结果
 6 
 7         # 有分组
 8 
 9         # 为何要有分组?提取匹配成功的指定内容(先匹配成功全部正则,再匹配成功的局部内容提取出来)
10 
11         r = re.match("h(\w+).*(?P<name>\d)$", origin)
12         print(r.group())     # 获取匹配到的所有结果
13         print(r.groups())    # 获取模型中匹配到的分组结果
14         print(r.groupdict()) # 获取模型中匹配到的分组中所有执行了key的组
15 
16 Demo
match
 1 # 无分组
 2 
 3         r = re.search("a\w+", origin)
 4         print(r.group())     # 获取匹配到的所有结果
 5         print(r.groups())    # 获取模型中匹配到的分组结果
 6         print(r.groupdict()) # 获取模型中匹配到的分组结果
 7 
 8         # 有分组
 9 
10         r = re.search("a(\w+).*(?P<name>\d)$", origin)
11         print(r.group())     # 获取匹配到的所有结果
12         print(r.groups())    # 获取模型中匹配到的分组结果
13         print(r.groupdict()) # 获取模型中匹配到的分组中所有执行了key的组
14 
15 demo
search
1         # 无分组
2         r = re.findall("a\w+",origin)
3         print(r)
4 
5         # 有分组
6         origin = "hello alex bcd abcd lge acd 19"
7         r = re.findall("a((\w*)c)(d)", origin)
8         print(r)
findall

 

  sub(换匹配成功的指定位置字符串)

 1 sub(pattern, repl, string, count=0, flags=0)
 2 
 3 # pattern: 正则模型
 4 
 5 # repl   : 要替换的字符串或可执行对象
 6 
 7 # string : 要匹配的字符串
 8 
 9 # count  : 指定匹配个数
10 
11 # flags  : 匹配模式
12 
13 
14 # 与分组无关
15 
16         origin = "hello alex bcd alex lge alex acd 19"
17             r = re.sub("a\w+", "999", origin, 2)
18             print(r)
sub知识

 

  split(根据正则匹配分割字符串)

 1 split(pattern, string, maxsplit=0, flags=0)
 2 
 3 # pattern: 正则模型
 4 
 5 # string : 要匹配的字符串
 6 
 7 # maxsplit:指定分割个数
 8 
 9 # flags  : 匹配模式
10 
11 
12  # 无分组
13         origin = "hello alex bcd alex lge alex acd 19"
14         r = re.split("alex", origin, 1)
15         print(r)
16 
17         # 有分组
18         
19         origin = "hello alex bcd alex lge alex acd 19"
20         r1 = re.split("(alex)", origin, 1)
21         print(r1)
22         r2 = re.split("(al(ex))", origin, 1)
23         print(r2)
24 
25 
26 IP:
27 ^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$
28 手机号:
29 ^1[3|4|5|8][0-9]\d{8}$
30 邮箱:
31 [a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+
32 
33 常用正则表达式
split

 分隔的结果

['hello ', 'alex', ' bcd alex lge alex acd 19']
['hello ', 'alex', 'ex', ' bcd alex lge alex acd 19']

   六、time(对时间操作)

时间相关的操作,时间有三种表示方式:

  • 时间戳               1970年1月1日之后的秒,即:time.time()
  • 格式化的字符串    2014-11-11 11:11,    即:time.strftime('%Y-%m-%d')
  • 结构化时间          元组包含了:年、日、星期等... time.struct_time    即:time.localtime()
print time.time()

print time.mktime(time.localtime())

   

print time.gmtime()    #可加时间戳参数

print time.localtime() #可加时间戳参数

print time.strptime('2014-11-11', '%Y-%m-%d')

   

print time.strftime('%Y-%m-%d') #默认当前时间

print time.strftime('%Y-%m-%d',time.localtime()) #默认当前时间

print time.asctime()

print time.asctime(time.localtime())

print time.ctime(time.time())

   

import datetime

'''

datetime.date:表示日期的类。常用的属性有year, month, day

datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond

datetime.datetime:表示日期时间

datetime.timedelta:表示时间间隔,即两个时间点之间的长度

timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

strftime("%Y-%m-%d")

'''

import datetime

print datetime.datetime.now()

print datetime.datetime.now() - datetime.timedelta(days=5)
time基本用法
%Y  Year with century as a decimal number.
    %m  Month as a decimal number [01,12].
    %d  Day of the month as a decimal number [01,31].
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %M  Minute as a decimal number [00,59].
    %S  Second as a decimal number [00,61].
    %z  Time zone offset from UTC.
    %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.
    %I  Hour (12-hour clock) as a decimal number [01,12].
    %p  Locale's equivalent of either AM or PM.

格式化占位符
格式化占位符

 

  七、json和pickle模块(序列化)

  

Python中用于序列化的两个模块

  • json     用于【字符串】和 【python基本数据类型】 间进行转换 (注:当字符串转Python数据类型时,字符串里的str数据类型必须用双引号
  • pickle   用于【python特有的类型】 和 【python基本数据类型】间进行转换
  • json与pickle在一定运用上是一致的

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

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

 1 import json
 2 
 3 dir_1 = {"name":"hgb","age":18}
 4 #dir change str
 5 str_1 = json.dumps(dir_1)
 6 
 7 print(str_1)
 8 
 9 #str change dir
10 dir_2 = json.loads(str_1)
json

 注:
  pickle 与 json
  pickle可以处理Python所有对象(用着存档)
  json只能处理Python基本数据类型(列表,元祖,字典,字符,int)

   八、XML模块(XML是实现不同语言或程序之间进行数据交换的协议)

XML文件格式如下:

<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对象


# 方法二:直接解析xml文件
from xml.etree import ElementTree as ET

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

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

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

2、操作XML(运用节点功能对节点的操作)

  1 class Element:
  2     """An XML element.
  3 
  4     This class is the reference implementation of the Element interface.
  5 
  6     An element's length is its number of subelements.  That means if you
  7     want to check if an element is truly empty, you should check BOTH
  8     its length AND its text attribute.
  9 
 10     The element tag, attribute names, and attribute values can be either
 11     bytes or strings.
 12 
 13     *tag* is the element name.  *attrib* is an optional dictionary containing
 14     element attributes. *extra* are additional element attributes given as
 15     keyword arguments.
 16 
 17     Example form:
 18         <tag attrib>text<child/>...</tag>tail
 19 
 20     """
 21 
 22     当前节点的标签名
 23     tag = None
 24     """The element's name."""
 25 
 26     当前节点的属性
 27 
 28     attrib = None
 29     """Dictionary of the element's attributes."""
 30 
 31     当前节点的内容
 32     text = None
 33     """
 34     Text before first subelement. This is either a string or the value None.
 35     Note that if there is no text, this attribute may be either
 36     None or the empty string, depending on the parser.
 37 
 38     """
 39 
 40     tail = None
 41     """
 42     Text after this element's end tag, but before the next sibling element's
 43     start tag.  This is either a string or the value None.  Note that if there
 44     was no text, this attribute may be either None or an empty string,
 45     depending on the parser.
 46 
 47     """
 48 
 49     def __init__(self, tag, attrib={}, **extra):
 50         if not isinstance(attrib, dict):
 51             raise TypeError("attrib must be dict, not %s" % (
 52                 attrib.__class__.__name__,))
 53         attrib = attrib.copy()
 54         attrib.update(extra)
 55         self.tag = tag
 56         self.attrib = attrib
 57         self._children = []
 58 
 59     def __repr__(self):
 60         return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self))
 61 
 62     def makeelement(self, tag, attrib):
 63         创建一个新节点
 64         """Create a new element with the same type.
 65 
 66         *tag* is a string containing the element name.
 67         *attrib* is a dictionary containing the element attributes.
 68 
 69         Do not call this method, use the SubElement factory function instead.
 70 
 71         """
 72         return self.__class__(tag, attrib)
 73 
 74     def copy(self):
 75         """Return copy of current element.
 76 
 77         This creates a shallow copy. Subelements will be shared with the
 78         original tree.
 79 
 80         """
 81         elem = self.makeelement(self.tag, self.attrib)
 82         elem.text = self.text
 83         elem.tail = self.tail
 84         elem[:] = self
 85         return elem
 86 
 87     def __len__(self):
 88         return len(self._children)
 89 
 90     def __bool__(self):
 91         warnings.warn(
 92             "The behavior of this method will change in future versions.  "
 93             "Use specific 'len(elem)' or 'elem is not None' test instead.",
 94             FutureWarning, stacklevel=2
 95             )
 96         return len(self._children) != 0 # emulate old behaviour, for now
 97 
 98     def __getitem__(self, index):
 99         return self._children[index]
100 
101     def __setitem__(self, index, element):
102         # if isinstance(index, slice):
103         #     for elt in element:
104         #         assert iselement(elt)
105         # else:
106         #     assert iselement(element)
107         self._children[index] = element
108 
109     def __delitem__(self, index):
110         del self._children[index]
111 
112     def append(self, subelement):
113         为当前节点追加一个子节点
114         """Add *subelement* to the end of this element.
115 
116         The new element will appear in document order after the last existing
117         subelement (or directly after the text, if it's the first subelement),
118         but before the end tag for this element.
119 
120         """
121         self._assert_is_element(subelement)
122         self._children.append(subelement)
123 
124     def extend(self, elements):
125         为当前节点扩展 n 个子节点
126         """Append subelements from a sequence.
127 
128         *elements* is a sequence with zero or more elements.
129 
130         """
131         for element in elements:
132             self._assert_is_element(element)
133         self._children.extend(elements)
134 
135     def insert(self, index, subelement):
136         在当前节点的子节点中插入某个节点,即:为当前节点创建子节点,然后插入指定位置
137         """Insert *subelement* at position *index*."""
138         self._assert_is_element(subelement)
139         self._children.insert(index, subelement)
140 
141     def _assert_is_element(self, e):
142         # Need to refer to the actual Python implementation, not the
143         # shadowing C implementation.
144         if not isinstance(e, _Element_Py):
145             raise TypeError('expected an Element, not %s' % type(e).__name__)
146 
147     def remove(self, subelement):
148         在当前节点在子节点中删除某个节点
149         """Remove matching subelement.
150 
151         Unlike the find methods, this method compares elements based on
152         identity, NOT ON tag value or contents.  To remove subelements by
153         other means, the easiest way is to use a list comprehension to
154         select what elements to keep, and then use slice assignment to update
155         the parent element.
156 
157         ValueError is raised if a matching element could not be found.
158 
159         """
160         # assert iselement(element)
161         self._children.remove(subelement)
162 
163     def getchildren(self):
164         获取所有的子节点(废弃)
165         """(Deprecated) Return all subelements.
166 
167         Elements are returned in document order.
168 
169         """
170         warnings.warn(
171             "This method will be removed in future versions.  "
172             "Use 'list(elem)' or iteration over elem instead.",
173             DeprecationWarning, stacklevel=2
174             )
175         return self._children
176 
177     def find(self, path, namespaces=None):
178         获取第一个寻找到的子节点
179         """Find first matching element by tag name or path.
180 
181         *path* is a string having either an element tag or an XPath,
182         *namespaces* is an optional mapping from namespace prefix to full name.
183 
184         Return the first matching element, or None if no element was found.
185 
186         """
187         return ElementPath.find(self, path, namespaces)
188 
189     def findtext(self, path, default=None, namespaces=None):
190         获取第一个寻找到的子节点的内容
191         """Find text for first matching element by tag name or path.
192 
193         *path* is a string having either an element tag or an XPath,
194         *default* is the value to return if the element was not found,
195         *namespaces* is an optional mapping from namespace prefix to full name.
196 
197         Return text content of first matching element, or default value if
198         none was found.  Note that if an element is found having no text
199         content, the empty string is returned.
200 
201         """
202         return ElementPath.findtext(self, path, default, namespaces)
203 
204     def findall(self, path, namespaces=None):
205         获取所有的子节点
206         """Find all matching subelements by tag name or path.
207 
208         *path* is a string having either an element tag or an XPath,
209         *namespaces* is an optional mapping from namespace prefix to full name.
210 
211         Returns list containing all matching elements in document order.
212 
213         """
214         return ElementPath.findall(self, path, namespaces)
215 
216     def iterfind(self, path, namespaces=None):
217         获取所有指定的节点,并创建一个迭代器(可以被for循环)
218         """Find all matching subelements by tag name or path.
219 
220         *path* is a string having either an element tag or an XPath,
221         *namespaces* is an optional mapping from namespace prefix to full name.
222 
223         Return an iterable yielding all matching elements in document order.
224 
225         """
226         return ElementPath.iterfind(self, path, namespaces)
227 
228     def clear(self):
229         清空节点
230         """Reset element.
231 
232         This function removes all subelements, clears all attributes, and sets
233         the text and tail attributes to None.
234 
235         """
236         self.attrib.clear()
237         self._children = []
238         self.text = self.tail = None
239 
240     def get(self, key, default=None):
241         获取当前节点的属性值
242         """Get element attribute.
243 
244         Equivalent to attrib.get, but some implementations may handle this a
245         bit more efficiently.  *key* is what attribute to look for, and
246         *default* is what to return if the attribute was not found.
247 
248         Returns a string containing the attribute value, or the default if
249         attribute was not found.
250 
251         """
252         return self.attrib.get(key, default)
253 
254     def set(self, key, value):
255         为当前节点设置属性值
256         """Set element attribute.
257 
258         Equivalent to attrib[key] = value, but some implementations may handle
259         this a bit more efficiently.  *key* is what attribute to set, and
260         *value* is the attribute value to set it to.
261 
262         """
263         self.attrib[key] = value
264 
265     def keys(self):
266         获取当前节点的所有属性的 key
267 
268         """Get list of attribute names.
269 
270         Names are returned in an arbitrary order, just like an ordinary
271         Python dict.  Equivalent to attrib.keys()
272 
273         """
274         return self.attrib.keys()
275 
276     def items(self):
277         获取当前节点的所有属性值,每个属性都是一个键值对
278         """Get element attributes as a sequence.
279 
280         The attributes are returned in arbitrary order.  Equivalent to
281         attrib.items().
282 
283         Return a list of (name, value) tuples.
284 
285         """
286         return self.attrib.items()
287 
288     def iter(self, tag=None):
289         在当前节点的子孙中根据节点名称寻找所有指定的节点,并返回一个迭代器(可以被for循环)。
290         """Create tree iterator.
291 
292         The iterator loops over the element and all subelements in document
293         order, returning all elements with a matching tag.
294 
295         If the tree structure is modified during iteration, new or removed
296         elements may or may not be included.  To get a stable set, use the
297         list() function on the iterator, and loop over the resulting list.
298 
299         *tag* is what tags to look for (default is to return all elements)
300 
301         Return an iterator containing all the matching elements.
302 
303         """
304         if tag == "*":
305             tag = None
306         if tag is None or self.tag == tag:
307             yield self
308         for e in self._children:
309             yield from e.iter(tag)
310 
311     # compatibility
312     def getiterator(self, tag=None):
313         # Change for a DeprecationWarning in 1.4
314         warnings.warn(
315             "This method will be removed in future versions.  "
316             "Use 'elem.iter()' or 'list(elem.iter())' instead.",
317             PendingDeprecationWarning, stacklevel=2
318         )
319         return list(self.iter(tag))
320 
321     def itertext(self):
322         在当前节点的子孙中根据节点名称寻找所有指定的节点的内容,并返回一个迭代器(可以被for循环)。
323         """Create text iterator.
324 
325         The iterator loops over the element and all subelements in document
326         order, returning all inner text.
327 
328         """
329         tag = self.tag
330         if not isinstance(tag, str) and tag is not None:
331             return
332         if self.text:
333             yield self.text
334         for e in self:
335             yield from e.itertext()
336             if e.tail:
337                 yield e.tail
338 
339 节点功能一览表
节点的功能

  a. 遍历XML文档的所有内容(for node in root:)

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)
获取所有节点信息

  b、遍历XML中指定的节点( for node in root.iter('指定节点'): )

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)
获取指定节点内容

   c、修改节点内容(把内存里修改后的xml对象重新writer一次)(删除属性:del root.year['name'])

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)

    # 设置属性
    node.set('name', 'alex')
    node.set('age', '18')
    # 删除属性
    del node.attrib['name']


############ 保存文件 ############
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)

    # 设置属性
    node.set('name', 'alex')
    node.set('age', '18')
    # 删除属性
    del node.attrib['name']


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

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

  两个方式区别:第一种方式把修改后的xml对象重新要解析回xml字符串(tree = ET.ElementTree(root))

  d、删除节点 : root.remove(country)

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)

    if rank > 50:
        # 删除指定country节点
        root.remove(country)

############ 保存文件 ############
tree = ET.ElementTree(root)
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()
View Code

 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")

命名空间
命名空间

 

   九、request模块(http请求),第三方模块

1、安装

  a.软件管理工具安装

  pip3 install requests

  b.源码安装

  1)下载源码包,解压源码包

  2)在python中,去到解压后的源码包目录,运行python stupe.exe install

2、使用模块

  基本用法:

import requests
 
ret = requests.get('https://github.com/timeline.json')
 
print(ret.url)
print(ret.text)
# 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请求
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请求
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)

其他请求
其他请求

 更多requests模块相关的文档见:http://cn.python-requests.org/zh_CN/latest/

 

  十、shutil模块(压缩、解压)

### 对文件或文件夹(内容,权限...)进行cope,和压缩(zipfile,tarfile) ###
 1 #10、创建压缩包并返回文件路径,例如:zip、tar
 2 #   创建压缩包并返回文件路径,例如:zip、tar
 3 #   base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
 4 #   如:www                        =>保存至当前路径
 5 #   如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
 6 #   format:    压缩包种类,“zip”, “tar”, “bztar”,“gztar”
 7 #   root_dir:    要压缩的文件夹路径(默认当前目录)
 8 #   owner:    用户,默认当前用户
 9 #   group:    组,默认当前组
10 #   logger:    用于记录日志,通常是logging.Logger对象
shutil知识点
 1 # 1、文件内容的cope
 2 #shutil.copyfileobj(open('con_file','r',encoding='utf-8'),open('new_file','w',encoding='utf-8'))
 3 
 4 # 2、文件cope
 5 shutil.copyfile('xml_file.xml','new_fil2')
 6 
 7 # 3、仅拷贝权限。内容、组、用户均不变
 8 shutil.copymode('f1.log', 'f2.log')
 9 
10 # 4、仅拷贝状态的信息,包括:mode bits, atime, mtime, flags
11 shutil.copystat('f1.log', 'f2.log')
12 
13 # 5、拷贝文件和权限
14 shutil.copy('f1.log', 'f2.log')
15 
16 # 6、拷贝文件和状态信息
17 shutil.copy2('f1.log', 'f2.log')
18 
19 #7、递归的去拷贝文件夹
20 shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
21 
22 #8、递归的去删除文件
23 shutil.rmtree('folder1')
24 
25 #9、递归的去移动文件,它类似mv命令,其实就是重命名
26 shutil.move('folder1', 'folder3')
ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/Downloads/test')
ret = shutil.make_archive("D:\\python/wwwwwwwwww", 'gztar', root_dir='/UsersDownloads/test')
 1 ### shutil 里调用了zipfile和tarfile模块 ###
 2 import zipfile
 3 
 4 # 压缩
 5 z = zipfile.ZipFile('laxi.zip', 'w')
 6 z.write('a.log')
 7 z.write('data.data')
 8 z.close()
 9 
10 # 解压
11 z = zipfile.ZipFile('laxi.zip', 'r')
12 z.extractall()
13 z.close()
14 
15 import tarfile
16 
17 # 压缩
18 tar = tarfile.open('your.tar','w')
19 tar.add('/Users/wupeiqi/PycharmProjects/bbs2.log', arcname='bbs2.log')
20 tar.add('/Users/wupeiqi/PycharmProjects/cmdb.log', arcname='cmdb.log')
21 tar.close()
22 
23 # 解压
24 tar = tarfile.open('your.tar','r')
25 tar.extractall()  # 可设置解压地址
26 tar.close()

 

  十一、subprocess模块(交互)

### subprocess模块 实现Python和其他系统(window,linux等)shell命令的交互
 1 import subprocess
 2 # 1、call 执行命令,返回状态码
 3 #sub = subprocess.call(["dir"],shell=False) 也会报错
 4 #sub0 = subprocess.call('dir')  该写法会报“系统找不到指定的文件。”
 5 # sub = subprocess.call('dir',shell=True)
 6 # print(sub)
 7 
 8 # 2、check_call 执行命令,如果执行状态码是 0 ,则返回0,否则抛异常
 9 # s2 = subprocess.check_call('ipconfig',shell=True)
10 # print(s2)
11 
12 # 3、执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常
13 # s2 = subprocess.check_output(["echo","happy!"],shell=True)
14 # s1 = subprocess.check_output("echo 'happy'",shell=True)
15 # s0 = subprocess.check_output('dir',shell=True)
16 # print(s0) #返回是字节
17 
18 ## 重点:用于执行复杂的系统命令(subprocess.Popen) ##
19 
20 # 1)简单命令
21 # ret1 = subprocess.Popen(["mkdir","t1"])
22 # ret2 = subprocess.Popen("mkdir t2", shell=True)
23 
24 # 2)到某个目录下,进行输入命令
25 # obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)
26 
27 # 3)输入进行某环境,依赖再输入,如:python
28 ### 方法一 ###
29 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
30 obj.stdin.write("print(1)\n")
31 obj.stdin.write("print(2)")
32 obj.stdin.close()
33 
34 cmd_out = obj.stdout.read()
35 obj.stdout.close()
36 cmd_error = obj.stderr.read()
37 obj.stderr.close()
38 
39 print(cmd_out)  #结果:1
40 print(cmd_error) #结果: 2
41 
42 ### 方法二 ###
43 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
44 obj.stdin.write("print(1)\n")
45 obj.stdin.write("print(2)")
46 
47 out_error_list = obj.communicate()
48 print(out_error_list) #结果:('1\n2\n', '')
49 
50 ### 方法三 ###
51 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
52 out_error_list = obj.communicate('print("hello")')
53 print(out_error_list) #结果:('hello\n', '')
subprocess运用

 

   十二、logging模块(日志管理)

### logging模块(用于便捷记录日志且线程安全的模块) ###
### 注:只有level【当前写等级】大于【日志等级】时,日志文件才被记录
 1 import logging
 2 
 3 #1、单文件日志
 4 """
 5 #定义写入日志的文本格式
 6 logging.basicConfig(filename='new_fil2',
 7                     format='%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s',
 8                     datefmt='%Y-%m-%d %H:%M:%S %p',
 9                     level=10)
10 logging.debug('debug')
11 logging.info('info')
12 logging.warning('warning')
13 logging.error('error')
14 logging.critical('critical')
15 #改命令可以设定level和写入的内容
16 logging.log(20,'log')
17 """
18 
19 # 2、多文件日志
20     ## 方法一 ##
21 """
22 # 定义文件
23 file_1_1 = logging.FileHandler('l1_1.log', 'a', encoding='utf-8')
24 ##定义写入日志文件里的文本格式(不用定义level)
25 fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s")
26 file_1_1.setFormatter(fmt)
27 
28 file_1_2 = logging.FileHandler('l1_2.log', 'a', encoding='utf-8')
29 fmt = logging.Formatter()  #没有定义内容,当文件输入时,只有要写入的内容
30 file_1_2.setFormatter(fmt)
31 
32 # 定义日志
33 logger1 = logging.Logger('s1', level=logging.ERROR) #定义name,定义level
34 logger1.addHandler(file_1_1)
35 logger1.addHandler(file_1_2)
36 
37 # 写日志
38 logger1.critical('1111')
39 """
40 
41     ## 方法二 ##
42 # 定义文件
43 file_2_1 = logging.FileHandler('l2_1.log', 'a')
44 fmt = logging.Formatter()
45 file_2_1.setFormatter(fmt)
46 
47 # 定义日志
48 logger2 = logging.Logger('s2', level=logging.INFO)
49 logger2.addHandler(file_2_1)
50 
51 # 写日志
52 logger2.critical('1111')
logging运用

 

   十三、configparser模块(配置文件操作)

 1 import configparser
 2 con = configparser.ConfigParser()
 3 # 步骤一(必须要有):打开一个文件
 4 red = con.read('con_file',encoding='utf-8')
 5 # print(red)
 6 # 获取文件的节点名称
 7 sec = con.sections()
 8 print(sec)
 9 # 对节点操作
10 # 1)判断节点,或节点里的key是否存在
11 has = con.has_section('sdy')
12 print(has)
13 tu = con.has_option('sdy','age')
14 print(tu)
15 # 2)设置节点,更改节点,删除节点
16 
17 # con.add_section('love')
18 # con.set('love','long','1314')
19 # con.set('love','Y/N','Y')
20 #con.write(open('con_file','w'))
21 
22 # con.remove_section('sb')
23 # con.write(open('con_file','w'))
24 
25 # 3)获取节点里的健值对
26 f0 = con.items('hgb')   #获取该节点所有健值对
27 f1 = con.options('hgb') #获取该节点的所有key值
28 f2 = con.get('hgb','age') #获取该节点的age里的value值 :getint;getfloat;getboolean
29 print(f0,f1,f2)
30 
31 # 4) 检查、删除、设置指定组内的键值对
32 # 删除
33 con.remove_option('section1', 'k1')
34 con.write(open('con_file', 'w'))
35 
36 # 设置( 没有就新增,有就修改)
37 con.set('section1', 'k10', "123")
38 con.write(open('con_file', 'w'))
运用

 

   十四、算法

    1、二叉堆(from pythonds.trees.binheap import BinHeap

BinaryHeap():创建一个空的二叉堆对象
insert(k):将新元素加入到堆中
findMin():返回堆中的最小项,最小项仍保留在堆中
delMin():返回堆中的最小项,同时从堆中删除
isEmpty():返回堆是否为空
size():返回堆中节点的个数
buildHeap(list):从一个包含节点的列表里创建新堆
基本操作
from pythonds.trees.binheap import BinHeap

bh = BinHeap()
bh.insert(5)
bh.insert(7)
bh.insert(3)
bh.insert(11)

print(bh.delMin())

print(bh.delMin())

print(bh.delMin())

print(bh.delMin())
例子

     

  十五、处理命令行传递的参数(argparse)

详细内容请查看:https://blog.ixxoo.me/argparse.html

 1 import argparse
 2 parser = argparse.ArgumentParser()
 3 parser.add_argument("square", type=int,
 4                     help="display the square of a given number")
 5 parser.add_argument("-v", "--verbosity", action="count",
 6                     help="increase output verbosity")
 7 args = parser.parse_args()
 8 answer = args.square**2
 9 if args.verbosity == 2:
10     print "the square of {} equals {}".format(args.square, answer)
11 elif args.verbosity == 1:
12     print "{}^2 == {}".format(args.square, answer)
13 else:
14     print answer
15 
16 # type -- 指定参数的类型(默认是字符串)
17 # "square" 指在文件里调用的名字,命令行无需传入参数名,(定位参数-必须要传入的参数)
18 # "-v", "--verbosity" -- 指定外面使用的参数名,文件里调用的是‘verbosity’(可选传入参数)
19 # help -- 指对参数做解析
20 # action -- 命令行传入参数名时,参数=action定义的值(特殊值
21                 action="store_true"-- 相当True
22                 ;action="count" -- 参数传入的个数)     
23 #choice -- 参数的取值范围       

 

   

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2017-10-21 21:26  浪子斌  阅读(556)  评论(0编辑  收藏  举报