目录python
1、安装、编译与运行正则表达式
2、变量、运算与表达式express
3、数据类型编程
一、数字api
二、字符串数组
三、元组app
四、列表ide
五、字典函数
4、流程控制oop
一、if-else
二、for
三、while
四、switch
5、函数
一、自定义函数
二、Lambda函数
三、Python内置函数
6、包与模块
一、模块module
二、包package
7、正则表达式
一、元字符
二、经常使用函数
三、分组
四、一个小实例-爬虫
8、深拷贝与浅拷贝
9、文件与目录
一、文件读写
二、OS模块
三、目录遍历
10、异常处理
1、安装、编译与运行
Python的安装很容易,直接到官网:http://www.python.org/下载安装就能够了。Ubuntu通常都预安装了。没有的话,就能够#apt-get install python。Windows的话直接下载msi包安装便可。Python 程序是经过解释器执行的,因此安装后,能够看到Python提供了两个解析器,一个是IDLE (Python GUI),一个是Python (command line)。前者是一个带GUI界面的版本,后者实际上和在命令提示符下运行python是同样的。运行解释器后,就会有一个命令提示符>>>,在提示符后键入你的程序语句,键入的语句将会当即执行。就像Matlab同样。
另外,Matlab有.m的脚步文件,python也有.py后缀的脚本文件,这个文件除了能够解释执行外,还能够编译运行,编译后运行速度要比解释运行要快。
例如,我要打印一个helloWorld。
方法1:直接在解释器中,>>> print ‘helloWorld’。
方法2:将这句代码写到一个文件中,例如hello.py。运行这个文件有三种方式:
1)在终端中:python hello.py
2)先编译成.pyc文件:
import py_compile
py_compile.compile("hello.py")
再在终端中:python hello.pyc
3)在终端中:
python -O -m py_compile hello.py
python hello.pyo
编译成.pyc和.pyo文件后,执行的速度会更快。因此通常一些重复性并屡次调用的代码会被编译成这两种可执行的方式来待调用。
2、变量、运算与表达式
这里没什么好说的,有其余语言的编程基础的话都没什么问题。和Matlab的类似度比较大。这块差异不是很大。具体以下:

须要注意的一个是:5/2 等于2,5.0/2才等于2.5。
- print 'Please input a number:'
- number = int(raw_input())
- number += 1
- print number**2
- print number and 1
- print number or 1
- print not number
- 5/2
- 5.0/2
3、数据类型
一、数字
一般的int, long,float,long等等都被支持。并且会看你的具体数字来定义变量的类型。以下:
- num = 1
- num = 1111111111111
- num = 1.0
- num = 12L
- num = 1 + 12j
- num = '1'
二、字符串
单引号,双引号和三引号均可以用来定义字符串。三引号能够定义特别格式的字符串。字符串做为一种序列类型,支持像Matlab同样的索引访问和切片访问。
- num = "1"
- num = "Let's go"
- num = "He's \"old\""
- mail = "Xiaoyi: \n hello \n I am you!"
- mail =
- string = 'xiaoyi'
- copy = string[0] + string[1] + string[2:6]
- copy = string[:4]
- copy = string[2:]
- copy = string[::1]
- copy = string[::2]
- copy = string[-1]
- copy = string[-4:-2:-1]
- memAddr = id(num)
- type(num)
三、元组
元组tuple用()来定义。至关于一个能够存储不一样类型数据的一个数组。能够用索引来访问,但须要注意的一点是,里面的元素不能被修改。
- firstName = 'Zou'
- lastName = 'Xiaoyi'
- len(string)
- name = firstName + lastName
- firstName * 3
- 'Z' in firstName
- string = '123'
- max(string)
- min(string)
- cmp(firstName, lastName)
-
- user = ("xiaoyi", 25, "male")
- name = user[0]
- age = user[1]
- gender = user[2]
- t1 = ()
- t2 = (2, )
- user[1] = 26
- name, age, gender = user
- a, b, c = (1, 2, 3)
四、列表
列表list用[]来定义。它和元组的功能同样,不一样的一点是,里面的元素能够修改。List是一个类,支持不少该类定义的方法,这些方法能够用来对list进行操做。
- userList = ["xiaoyi", 25, "male"]
- name = userList[0]
- age = userList[1]
- gender = userList[2]
- userList[3] = 88888
- userList.append(8888)
- "male" in userList
- userList[2] = 'female'
- userList.remove(8888)
- userList.remove(userList[2])
- del(userList[1])
-
五、字典
字典dictionary用{}来定义。它的优势是定义像key-value这种键值对的结构,就像struct结构体的功能同样。它也支持字典类支持的方法进行建立和操做。
- item = ['name', 'age', 'gender']
- value = ['xiaoyi', '25', 'male']
- zip(item, value)
- dic = {'name': 'xiaoyi', 'age': 25, 'gender': 'male'}
- dic = {1: 'zou', 'age':25, 'gender': 'male'}
- print dic['name']
- print dic[1]
- fdict = dict(['x', 1], ['y', 2])
- ddict = {}.fromkeys(('x', 'y'), -1)
- for key in dic
- print key
- print dic[key]
-
- dic['tel'] = 88888
- del dic[1]
- dic.pop('tel')
- dic.clear()
- del dic
- dic.get(1)
- dic.get(1, 'error')
- dic.keys()
- dic.values()
- dic.has_key(key)
4、流程控制
在这块,Python与其它大多数语言有个很是不一样的地方,Python语言使用缩进块来表示程序逻辑(其它大多数语言使用大括号等)。例如:
if age < 21:
print("你不能买酒。")
print("不过你能买口香糖。")
print("这句话处于if语句块的外面。")
这个代码至关于c语言的:
if (age < 21)
{
print("你不能买酒。")
print("不过你能买口香糖。")
}
print("这句话处于if语句块的外面。")
能够看到,Python语言利用缩进表示语句块的开始和退出(Off-side规则),而非使用花括号或者某种关键字。增长缩进表示语句块的开始(注意前面有个:号),而减小缩进则表示语句块的退出。根据PEP的规定,必须使用4个空格来表示每级缩进(不清楚4个空格的规定如何,在实际编写中能够自定义空格数,可是要知足每级缩进间空格数相等)。使用Tab字符和其它数目的空格虽然均可以编译经过,但不符合编码规范。
为了使咱们本身编写的程序能很好的兼容别人的程序,咱们最好仍是按规范来,用四个空格来缩减(注意,要么都是空格,要是么都制表符,千万别混用)。
一、if-else
If-else用来判断一些条件,以执行知足某种条件的代码。
- if expression:
- statement(s)
-
- if expression:
- statement(s)
-
- if 1<2:
- print 'ok, '
- print 'yeah'
-
- if True:
- print 'true'
-
- def fun():
- return 1
-
- if fun():
- print 'ok'
- else:
- print 'no'
-
- con = int(raw_input('please input a number:'))
- if con < 2:
- print 'small'
- elif con > 3:
- print 'big'
- else:
- print 'middle'
-
- if 1 < 2:
- if 2 < 3:
- print 'yeah'
- else:
- print 'no'
- print 'out'
- else:
- print 'bad'
-
- if 1<2 and 2<3 or 2 < 4 not 0:
- print 'yeah'
二、for
for的做用是循环执行某段代码。还能够用来遍历咱们上面所提到的序列类型的变量。
- for iterating_val in sequence:
- statements(s)
-
- for i in "abcd":
- print i
-
- for i in [1, 2, 3, 4]:
- print i
-
- range(5)
- range(1, 5)
- range(1, 10, 2)
- for i in range(1, 100, 1):
- print i
-
- fruits = ['apple', 'banana', 'mango']
- for fruit in range(len(fruits)):
- print 'current fruit: ', fruits[fruit]
-
- dic = {1: 111, 2: 222, 5: 555}
- for x in dic:
- print x, ': ', dic[x]
-
- dic.items()
- for key,value in dic.items():
- print key, ': ', value
- else:
- print 'ending'
-
- import time
- for x in range(1, 11):
- print x
- time.sleep(1)
- if x == 3:
- pass
- if x == 2:
- continue
- if x == 6:
- break
- if x == 7:
- exit()
- print '#'*50
三、while
while的用途也是循环。它首先检查在它后边的循环条件,若条件表达式为真,它就执行冒号后面的语句块,而后再次测试循环条件,直至为假。冒号后面的缩近语句块为循环体。
- while expression:
- statement(s)
-
- while True:
- print 'hello'
- x = raw_input('please input something, q for quit:')
- if x == 'q':
- break
- else:
- print 'ending'
四、switch
其实Python并无提供switch结构,但咱们能够经过字典和函数轻松的进行构造。例如:
-
- from __future__ import division
-
- def add(x, y):
- return x + y
- def sub(x, y):
- return x - y
- def mul(x, y):
- return x * y
- def div(x, y):
- return x / y
-
- operator = {"+": add, "-": sub, "*": mul, "/": div}
- operator["+"](1, 2)
- operator["%"](1, 2)
- operator.get("+")(1, 2)
-
- def cal(x, o, y):
- print operator.get(o)(x, y)
- cal(2, "+", 3)
5、函数
一、自定义函数
在Python中,使用def语句来建立函数:
- def functionName(parameters):
- bodyOfFunction
-
- def add(a, b):
- return a+b
-
- a = 100
- b = 200
- sum = add(a, b)
-
- def add(a = 1, b = 2):
- return a+b
- add()
- add(2)
- add(y = 1)
- add(3, 4)
-
- val = 100
- def fun():
- print val
- print val
-
- def fun():
- a = 100
- print a
- print a
-
- def fun():
- global a = 100
- print a
-
- print a
- fun()
- print a
-
- def fun(x):
- print x
- fun(10)
- fun('hello')
- fun(('x', 2, 3))
- fun([1, 2, 3])
- fun({1: 1, 2: 2})
-
- def fun(x, y):
- print "%s : %s" % (x,y)
- fun('Zou', 'xiaoyi')
- tu = ('Zou', 'xiaoyi')
- fun(*tu)
-
- def fun(name = "name", age = 0):
- print "name: %s" % name
- print "age: " % age
- dic = {name: "xiaoyi", age: 25}
- fun(**dic)
- fun(age = 25, name = 'xiaoyi')
-
- def fun(x, *args):
- print x
- print args
- fun(10)
- fun(10, 12, 24)
-
- def fun(x, **args):
- print x
- print args
- fun(10)
- fun(x = 10, y = 12, z = 15)
-
- def fun(x, *args, **kwargs):
- print x
- print args
- print kwargs
- fun(1, 2, 3, 4, y = 10, z = 12)
二、Lambda函数
Lambda函数用来定义一个单行的函数,其便利在于:
- fun = lambda x,y : x*y
- fun(2, 3)
- def fun(x, y):
- return x*y
-
- def recursion(n):
- if n > 0:
- return n * recursion(n-1)
-
- def mul(x, y):
- return x * y
- numList = range(1, 5)
- reduce(mul, numList)
- reduce(lambda x,y : x*y, numList)
-
- numList = [1, 2, 6, 7]
- filter(lambda x : x % 2 == 0, numList)
- print [x for x in numList if x % 2 == 0]
- map(lambda x : x * 2 + 10, numList)
- print [x * 2 + 10 for x in numList]
三、Python内置函数
Python内置了不少函数,他们都是一个个的.py文件,在python的安装目录能够找到。弄清它有那些函数,对咱们的高效编程很是有用。这样就能够避免重复的劳动了。下面也只是列出一些经常使用的:
- abs, max, min, len, divmod, pow, round, callable,
- isinstance, cmp, range, xrange, type, id, int()
- list(), tuple(), hex(), oct(), chr(), ord(), long()
-
- callable
-
- isinstance
- numList = [1, 2]
- if type(numList) == type([]):
- print "It is a list"
- if isinstance(numList, list):
- print "It is a list"
-
- for i in range(1, 10001)
- for i in xrange(1, 10001)
-
- str = 'hello world'
- str.capitalize()
- str.replace("hello", "good")
- ip = "192.168.1.123"
- ip.split('.')
- help(str.split)
-
- import string
- str = 'hello world'
- string.replace(str, "hello", "good")
-
- len, max, min
- def fun(x):
- if x > 5:
- return True
- numList = [1, 2, 6, 7]
- filter(fun, numList)
- filter(lambda x : x % 2 == 0, numList)
- name = ["me", "you"]
- age = [25, 26]
- tel = ["123", "234"]
- zip(name, age, tel)
- map(None, name, age, tel)
- test = ["hello1", "hello2", "hello3"]
- zip(name, age, tel, test)
- map(None, name, age, tel, test)
- a = [1, 3, 5]
- b = [2, 4, 6]
- def mul(x, y):
- return x*y
- map(mul, a, b)
- reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])