python基础训练营05

任务五 时长:2天

1.file

a.打开文件方式(读写两种方式)

b.文件对象的操作方法

c.学习对excel及csv文件进行操作

2.os模块

3.datetime模块

4.类和对象

5.正则表达式

6.re模块

7.http请求

1. File
A. 打开文件方式
打开文件用 open() 的方式,注意:打开前一定要确定关闭文件对象,即用 close() 的用法。

open()函数常用形式是只接受两个参数:文件名(file)和模式(mode):

open(file, mode='r')
1
完整的语法格式为:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
1
参数说明:

file: 必需,文件路径(相对或者绝对路径)。
mode: 可选,文件打开模式
buffering: 设置缓冲
encoding: 一般使用utf8
errors: 报错级别
newline: 区分换行符
closefd: 传入的file参数类型
opener:

B. 文件对象的操作方法

当我们用 open() 打开文件对象后,还可以用以下le对象来进行操作:

2. OS模块
os 模块提供了非常丰富的方法用来处理文件和目录,共有64种,详情可见以下:http://www.runoob.com/python3/python3-os-file-methods.html。

3. Datetime模块
datetime模块定义了下面这几个类:

datetime.date:表示日期的类。常用的属性有year, month, day;
datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond;
datetime.datetime:表示日期时间。
datetime.timedelta:表示时间间隔,即两个时间点之间的长度。
datetime.tzinfo:与时区有关的相关信息。

>>> from datetime import *
>>> date.today()*获取今天的日期
datetime.date(2013, 10, 25)
>>> datetime.today()#获取今天的日期和时间
datetime.datetime(2013, 10, 25, 13, 42, 53, 455000)
>>> datetime.now()#获取当前的日期和时间
datetime.datetime(2013, 10, 25, 13, 43, 0, 322000)
1
2
3
4
5
6
7
datetime.fromtimestamp(time.time())#将时间戳转换为字符串

from datetime import *
import time

print 'datetime.max:', datetime.max
print 'datetime.min:', datetime.min
print 'datetime.resolution:', datetime.resolution
print 'today():', datetime.today()
print 'now():', datetime.now()
print 'utcnow():', datetime.utcnow()
print 'fromtimestamp(tmstmp):', datetime.fromtimestamp(time.time())#将时间戳转换为字符串
print 'utcfromtimestamp(tmstmp):', datetime.utcfromtimestamp(time.time())

# ---- 结果 ----
# datetime.max: 9999-12-31 23:59:59.999999
# datetime.min: 0001-01-01 00:00:00
# datetime.resolution: 0:00:00.000001
# today(): 2010-04-07 09:48:16.234000
# now(): 2010-04-07 09:48:16.234000
# utcnow(): 2010-04-07 01:48:16.234000 # 中国位于+8时间,与本地时间相差8
# fromtimestamp(tmstmp): 2010-04-07 09:48:16.234000
# utcfromtimestamp(tmstmp): 2010-04-07 01:48:16.234000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
4. 类和对象
参考一篇在当初自学python时看过的,对类和对象非常好的解释。作者:John Philip Jones,翻译地址:https://www.cnblogs.com/magicking/p/8971740.html。

5. 正则表达式
正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。

runoo+b,可以匹配 runoob、runooob、runoooooob 等,+ 号代表前面的字符必须至少出现一次(1次或多次)。

runoob,可以匹配 runob、runoob、runoooooob 等, 号代表字符可以不出现,也可以出现一次或者多次(0次、或1次、或多次)。

colou?r 可以匹配 color 或者 colour,? 问号代表前面的字符最多只可以出现一次(0次、或1次)。

5.1 普通字符

普通字符包括没有显式指定为元字符的所有可打印和不可打印字符。这包括所有大写和小写字母、所有数字、所有标点符号和一些其他符号。

5.2 非打印字符

非打印字符也可以是正则表达式的组成部分。下表列出了表示非打印字符的转义序列:

5.3 特殊字符

所谓特殊字符,就是一些有特殊含义的字符,如上面说的 runoo*b 中的 ,简单的说就是表示任何字符串的意思。如果要查找字符串中的 * 符号,则需要对 * 进行转义,即在其前加一个 : runo*ob 匹配 runoob。

许多元字符要求在试图匹配它们时特别对待。若要匹配这些特殊字符,必须首先使字符"转义",即,将反斜杠字符\ 放在它们前面。下表列出了正则表达式中的特殊字符:


5.4 限定符

限定符用来指定正则表达式的一个给定组件必须要出现多少次才能满足匹配。有 * 或 + 或 ? 或 {n} 或 {n,} 或 {n,m} 共6种。

正则表达式的限定符有:


6. Re模块
正则表达式本身是一种小型的、高度专业化的编程语言,而在python中,通过内嵌集成re模块,程序媛们可以直接调用来实现正则匹配。正则表达式模式被编译成一系列的字节码,然后由用C编写的匹配引擎执行。
re模块中常用功能函数
1、compile()

编译正则表达式模式,返回一个对象的模式。(可以把那些常用的正则表达式编译成正则表达式对象,这样可以提高一点效率。)
格式:

re.compile(pattern,flags=0)

pattern: 编译时用的表达式字符串。

import re
tt = "Tina is a good girl, she is cool, clever, and so on..."
rr = re.compile(r'\w*oo\w*')
print(rr.findall(tt)) #查找所有包含'oo'的单词
执行结果如下:
['good', 'cool']
1
2
3
4
5
6
2、match()

决定RE是否在字符串刚开始的位置匹配。//注:这个方法并不是完全匹配。当pattern结束时若string还有剩余字符,仍然视为成功。想要完全匹配,可以在表达式末尾加上边界匹配符’$’

格式:

re.match(pattern, string, flags=0)

print(re.match('com','comwww.runcomoob').group())
print(re.match('com','Comwww.runcomoob',re.I).group())
执行结果如下:
com
com
1
2
3
4
5
3、search()

格式:

re.search(pattern, string, flags=0)

re.search函数会在字符串内查找模式匹配,只要找到第一个匹配然后返回,如果字符串没有匹配,则返回None。

print(re.search('\dcom','www.4comrunoob.5com').group())
执行结果如下:
4com
1
2
3
4、findall()

re.findall遍历匹配,可以获取字符串中所有匹配的字符串,返回一个列表。

格式:

re.findall(pattern, string, flags=0)

p = re.compile(r'\d+')
print(p.findall('o1n2m3k4'))
执行结果如下:
['1', '2', '3', '4']
1
2
3
4
5、finditer()

搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。找到 RE 匹配的所有子串,并把它们作为一个迭代器返回。

格式:

re.finditer(pattern, string, flags=0)

iter = re.finditer(r'\d+','12 drumm44ers drumming, 11 ... 10 ...')
for i in iter:
print(i)
print(i.group())
print(i.span())
执行结果如下:
<_sre.SRE_Match object; span=(0, 2), match='12'>
12
(0, 2)
<_sre.SRE_Match object; span=(8, 10), match='44'>
44
(8, 10)
<_sre.SRE_Match object; span=(24, 26), match='11'>
11
(24, 26)
<_sre.SRE_Match object; span=(31, 33), match='10'>
10
(31, 33)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
6、split()

按照能够匹配的子串将string分割后返回列表。

可以使用re.split来分割字符串,如:re.split(r’\s+’, text);将字符串按空格分割成一个单词列表。

格式:

re.split(pattern, string[, maxsplit])

maxsplit用于指定最大分割次数,不指定将全部分割。

print(re.split('\d+','one1two2three3four4five5'))
执行结果如下:
['one', 'two', 'three', 'four', 'five', '']
1
2
3
7、sub()

使用re替换string中每一个匹配的子串后返回替换后的字符串。

格式:

re.sub(pattern, repl, string, count)

import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
print(re.sub(r'\s+', '-', text))
执行结果如下:
JGood-is-a-handsome-boy,-he-is-cool,-clever,-and-so-on...
其中第二个函数是替换后的字符串;本例中为'-'

第四个参数指替换个数。默认为0,表示每个匹配项都替换。
1
2
3
4
5
6
7
8
8、subn()

返回替换次数

格式:

subn(pattern, repl, string, count=0, flags=0)

print(re.subn('[1-2]','A','123456abcdef'))
print(re.sub("g.t","have",'I get A, I got B ,I gut C'))
print(re.subn("g.t","have",'I get A, I got B ,I gut C'))
执行结果如下:
('AA3456abcdef', 2)
I have A, I have B ,I have C
('I have A, I have B ,I have C', 3)
1
2
3
4
5
6
7
7. http请求
一、python自带库----urllib2

python自带库urllib2使用的比较多,简单使用如下:

import urllib2
response = urllib2.urlopen('http://localhost:8080/jenkins/api/json?pretty=true')
print response.read()
1
2
3
简单的get请求

import urllib2
import urllib
post_data = urllib.urlencode({})
response = urllib2.urlopen('http://localhost:8080/, post_data)
print response.read()
print response.getheaders()
1
2
3
4
5
6
这就是最简单的urllib2发送post例子。代码比较多

二、python自带库–httplib

httplib是一个相对底层的http请求模块,urlib就是基于httplib封装的。简单使用如下:

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("GET", "/index.html")
r1 = conn.getresponse()
print r1.status, r1.reason
data1 = r1.read()
conn.request("GET", "/parrot.spam")
r2 = conn.getresponse()
data2 = r2.read()
conn.close()
1
2
3
4
5
6
7
8
9
10
简单的get请求

我们再来看post请求

import httplib, urllib
params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}

conn = httplib.HTTPConnection("bugs.python.org")
conn.request("POST", "", params, headers)
response = conn.getresponse()
data = response.read()
print data
conn.close()
1
2
3
4
5
6
7
8
9
10
是不是觉得太复杂了。每次写还得再翻文档,看看第三种吧

三、第三方库–requests

发请get请求超级简单:

print requests.get('http://localhost:8080).text
1
就一句话,再来看看post请求

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print r.text
1
2
3
也很简单。

猜你喜欢

转载自www.cnblogs.com/tommyngx/p/10681214.html