<python基础教程(第二版)>html
http://www.cnblogs.com/fnng/category/454439.htmlpython
eg:web
>>> numbers = [0,1,2,3,4,5,6,7,8,9]正则表达式
>>> numbers[7:-1] shell
===================================小程序
[] --> 列表数组
()--> 元组多线程
===================================app
dict函数框架
能够用dict 函数,经过其余映射(好比其余字典)或(键,值)这样的序列对创建字典。
eg:
>>> items = [('name','gumby'),('age',42)] >>> d = dict(items) >>> d {'age': 42, 'name': 'gumby'} >>> d['name'] 'gumby'
===================================
>>> scoundrel ={'name':'robin','girlfriend':'marion'} >>> key,value = scoundrel.popitem() >>> key 'name' >>> value 'robin'
>>> x += 1 #(x=x+1) >>> x *= 2 #(x=x*2)
d = {'x':1,'y':2,'z':3} for key in d: print key,'corresponds to',d[key] #输出 >>> y corresponds to 2 x corresponds to 1 z corresponds to 3
from math import sqrt for n in range(99,0,-1): root = sqrt(n) if root == int(root): print n break #输出 >>> 81
==========================================================================================
默认参数 对于一些参数,咱们但愿它的一些参数是可选的,若是用户不想要为这些参数提供值的话,这些参数就使用默认值。
def say(message,times=1): print message*times say('Hello') say('World',5) #输出 >>> Hello WorldWorldWorldWorldWorld
def func(a,b=5,c=10): print 'a is',a, 'and b is',b,'and c is',c func(3,7) func(24,c=32) func(c=23,a=14)
=======================================================
>>> def add(x,y): return x+y >>> add(1,2) 3 >>> add('hello.','world') 'hello.world'
>>> def length_message(x):
print"The length of " , repr(x),"is",len(x)
>>> length_message('chongshi') The length of 'chongshi' is 8
==================================================================
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!"
class MuffledCalulator: muffled = False #这里默认关闭屏蔽 def calc(self,expr): try: return eval(expr) except ZeroDivisionError: if self.muffled: print 'Divsion by zero is illagal' else: raise #运行程序: >>> calculator = MuffledCalulator() >>> calculator.calc('10/2') 5 >>> calculator.clac('10/0') Traceback (most recent call last): File "<pyshell#30>", line 1, in <module> calculator.clac('10/0') AttributeError: MuffledCalulator instance has no attribute 'clac' #异常信息被输出了 >>> calculator.muffled = True #如今打开屏蔽 >>> calculator.calc('10/0') Divsion by zero is illagal
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!" except TypeError: # 对字符的异常处理 print "请输入数字!"
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except (ZeroDivisionError,TypeError,NameError): print "你的数字不对!"
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except: print '有错误发生了!'
====================================
构造方法
构造方法与其的方法不同,当一个对象被建立会当即调用构造方法。建立一个python的构造方法很简答,只要把init方法,从简单的init方法,转换成魔法版本的_init_方法就能够了。
class FooBar: def __init__(self): self.somevar = 42 >>> f =FooBar() >>> f.somevar 42
调用未绑定的超类构造方法
使用super函数
super函数只能在新式类中使用。当前类和对象能够做为super函数的参数使用,调用函数返回的对象的任何方法都是调用超类的方法,而不是当前类的方法。那就能够不一样在SongBird的构造方法中使用Bird,而直接使用super(SongBird,self)。
... super(SongBird,self).__init__() ...
def __init__(self): self.width = 0 self.height = 0
=========================================================
迭代器(无限循环)
迭代的意思是重复作一些事不少次---就像在循环中作的那样。__iter__ 方法返回一个迭代器,所谓迭代器就是具备next方法的对象,在调用next方法时,迭代器会返回它的下一个值。若是next方法被调用,但迭代器没有值能够返回,就会引起一个StopIteration异常。
class Fibs: def __init__(self): self.a = 0 self.b = 1 def next(self): self.a , self.b = self.b , self.a + self.b return self.a def __iter__(self): return self >>> fibs = Fibs() >>> for f in fibs: if f > 1000: print f break #由于设置了break ,因此循环在这里中止。 1597
class TestIterator: value = 0 def next(self): self.value += 1 if self.value > 10: raise StopIteration return self.value def __iter__(self): return self >>> ti = TestIterator() >>> list(ti) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
生成器也叫 简单生成器,生成器能够帮助读者写出很是优雅的代码,固然,编写任何程序时不使用生成器也是能够的。
>>> def flatten(nested): for sublist in nested: for element in sublist: yield element >>> nested = [[1,2],[3,4],[5]] #使用for循环 >>> for num in flatten(nested): print num 1 2 3 4 5
生成器新属性是在开始运行后为生成器提供值的能力。表现为生成器和“外部世界”进行交流的渠道:
* 外部做用域访问生成器的send方法,就像访问next 方法同样,只不过前者使用一个参数(发送的“消息”---任意对象)
* 在内部则挂起生成器,yield如今做为表达式而不是语句使用,换句话说,当生成器从新运行的时候,yield方法返回一个值,也就是外部经过send方法发送的值。若是next 方法被使用,那么yield方法返回None.
下面简单的方例子来讲明这种机制:
def repeater(value): while True: new =(yield value) if new is not None:value = new >>> r = repeater(42) >>> r.next() 42 >>> r.send("hello, world!") 'hello, world!'
生成器的另两个方法:
* throw方法(使用异常类型调用,还有可选的值以及回溯对象)用于在生成器内引起一个异常(在yield表达式中)
* close 方法(调用时不用参数)用于中止生成器。
>>> import sys >>> sys.path.append('c:/python') >>> import hello hello,world!
python文件的后缀为.py ,.py文件能够用来直接运行,就像一个独立的小程序;也能够用来做为模块被其它程序调用。
__name__是模块的内置属性,若是等于'__main__' 侧表示直接被使用,那么将执行方法test()方法;若是是被调用则不执行 if 判断后面的test()方法。
time.asctime()
'Thu May 16 00:00:08 2013'
random模块包括返回随机的函数,能够用于模拟或者用于任何产生随机输出的程序。
random模块中的一些重要函数:
** 通配符
正则表达式能够匹配多于一个的字符串,你可使用一些特殊字符建立这类模式。好比点号(.)能够匹配任何字符。在咱们用window 搜索时用问号(?)匹配任意一位字符,做用是同样的。那么这类符号就叫 通配符。
** 对特殊字符进行转义
使用“python\\.org”,这样就只会匹配“python.org”了
** 字符集
咱们可使用中括号([ ])括住字符串来建立字符集。可使用范围,好比‘[a-z]’可以匹配a到z的任意一个字符,还能够经过一个接一个的方式将范围联合起来使用,好比‘[a-zA-Z0-9]’可以匹配任意大小写字母和数字。
反转字符集,能够在开头使用^字符,好比‘[^abc]’能够匹配任何除了a、b、c以外的字符。
** 选择符
有时候只想匹配字符串’python’ 和 ’perl’ ,可使用选择项的特殊字符:管道符号(|) 。所以, 所需模式能够写成’python|perl’ 。
** 子模式(加括号)
可是,有些时候不须要对整个模式使用选择符---只是模式的一部分。这时可使用圆括号起须要的部分,或称子模式。 前例能够写成 ‘p(ython | erl)’
** 可选项
在子模式后面加上问号,它就变成了可选项。它可能出如今匹配字符串,但并不是必须的。
** 重复子模式
(pattern)* : 容许模式重复0次或屡次
(pattern)+ : 容许模式重复1次或屡次
(pattern){m,n} : 容许模式重复m~ n 次
re模块中一些重要的函数:
re.split 会根据模式的匹配项来分割字符串。
re. findall以列表形式返回给定模式的全部匹配项。
re.sub的做用在于:使用给定的替换内容将匹配模式的子符串(最左端而且重叠子字符串)替换掉。
re.escape 函数,能够对字符串中全部可能被解释为正则运算符的字符进行转义的应用函数。若是字符串很长且包含不少特殊字符,而你又不想输入一大堆反斜线,可使用这个函数。
简单来讲,组就是放置在圆括号里内的子模块,组的序号取决于它左侧的括号数。
re 匹配对象的重要方法
=========================================================
open函数中模式参数的经常使用值
readline返回一行的字符串, readlines返回包含文件全部内容的字符串列表, 每一个元素是一行的字符串。
pprint 模块的pprint方法将内容分红每一个小项单行显示。
>>> f = open(r'I:\python\test.txt') >>> lines = f.readlines() >>> lines[1] = "isn't a\n" >>> f = open(r'I:\python\test.txt','w') >>> f.writelines(lines) >>> f.close()
>>> first,second,third = open(r'I:\python\test.txt') >>> first 'First line\n' >>> second 'Second line\n' >>> third 'Third line\n'
===========================================================================================================
图形用户界面
import wx # 须要导入wx模块 app = wx.App() win = wx.Frame(None) win.Show() app.MainLoop()
假设写了一个负责打开文件的函数,并将其命令为load ,而后就能够像下面这样将函数做为loadButton的事件处理函数:
loadButton.Bind(wx.EVT_BUTTON,load)
================================================================
什么是进程?
计算机程序只不过是磁盘中可执行的,二进制(或其它类型)的数据。它们只有在被读取到内存中,被操做系统调用的时候才开始它们的生命期。进程(有时被称为重量级进程)是程序的一次执行。每一个进程都有本身的地址空间,内存,数据栈以及其它记录其运行轨迹的辅助数据。操做系统管理在其上运行的全部进程,并为这些进程公平地分配时间。
什么是线程?
线程(有时被称为轻量级进程)跟进程有些类似,不一样的是,全部的线程运行在同一个进程中,共享相同的运行环境。咱们能够想像成是在主进程或“主线程”中并行运行的“迷你进程”。
thread.allocate_lock()
返回一个新的锁定对象。
acquire() /release()
一个原始的锁有两种状态,锁定与解锁,分别对应acquire()和release() 方法。
thread.start_new_thread(loop0, ())
#coding=utf-8 import thread from time import sleep, ctime loops = [4,2] def loop(nloop, nsec, lock): print 'start loop', nloop, 'at:', ctime() sleep(nsec) print 'loop', nloop, 'done at:', ctime() #解锁 lock.release() def main(): print 'starting at:', ctime() locks =[] #以loops数组建立列表,并赋值给nloops nloops = range(len(loops)) for i in nloops: lock = thread.allocate_lock() #锁定 lock.acquire() #追加到locks[]数组中 locks.append(lock) #执行多线程 for i in nloops: thread.start_new_thread(loop,(i,loops[i],locks[i])) for i in nloops: while locks[i].locked(): pass print 'all end:', ctime() if __name__ == '__main__': main()
__init__()
方法在类的一个对象被创建时运行。这个方法能够用来对你的对象作一些初始化。
apply()
apply(func [, args [, kwargs ]]) 函数用于当函数参数已经存在于一个元组或字典中时,间接地调用函数。args是一个包含将要提供给函数的按位置传递的参数的元组。若是省略了args,任何参数都不会被传递,kwargs是一个包含关键字参数的字典。
apply() 用法:
#不带参数的方法 >>> def say(): print 'say in' >>> apply(say) say in #函数只带元组的参数 >>> def say(a,b): print a,b >>> apply(say,('hello','虫师')) hello 虫师 #函数带关键字参数 >>> def say(a=1,b=2): print a,b >>> def haha(**kw): apply(say,(),kw) >>> haha(a='a',b='b') a b
===================================
re.compile() 能够把正则表达式编译成一个正则表达式对象.
re.findall() 方法读取html 中包含 imgre(正则表达式)的数据。
#coding=utf-8 import urllib import re def getHtml(url): page = urllib.urlopen(url) html = page.read() return html def getImg(html): reg = r'src="(.+?\.jpg)" pic_ext' imgre = re.compile(reg) imglist = re.findall(imgre,html) x = 0 for imgurl in imglist: urllib.urlretrieve(imgurl,'%s.jpg' % x) x+=1 html = getHtml("http://tieba.baidu.com/p/2460150866") print getImg(html)
=================================================
什么是xml?
xml便可扩展标记语言,它能够用来标记数据、定义数据类型,是一种容许用户对本身的标记语言进行定义的源语言。
从结构上,它很像咱们常见的HTML超文本标记语言。但他们被设计的目的是不一样的,超文本标记语言被设计用来显示数据,其焦点是数据的外观。它被设计用来传输和存储数据,其焦点是数据的内容。
<aa>
<bb></bb>
</aa>