python基础

来源:互联网 发布:淘宝电动车加热手套 编辑:程序博客网 时间:2024/06/05 03:49

1、python有三种文件类型

(1).py

python源码文件

(2).pyc

编译后的文件,通过下面的命令编译

import py_compile
py_compile.compile('hello.py')

( 3).pyo

优化后的源文件

python -O -m py_compile hello.py


2、python数据结构

字符串(String)  值不能改变  str1=’abcd‘

元组(tuple)值不能改变 tup1=(’abc‘,’bcd‘)

列表(list)值可以改变 list1=[’abc‘,’bcd‘],取值,添加,修改,删除,查找

字典(dic)key不能改变,value可以改变dic1={’name‘:’xx‘,’age’:25}  ,对键值的更新和删除,大小的比较,遍历


3、python的流控

3.1 if判断

if xx:

  xx

elif xx:

  xx

else:

  xx

3.2 for循环

for x in “xxx”:

   xx

else:

  xx

for k,v in dic.items():

  xx

else:

  xx

可以通过range生成循环个数

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> range(2,10,3)
[2, 5, 8]

3.3 while循环

while xx:

   xx

else:

  xx

可以通过help(list.append)去查看函数使用方法


4、函数

函数定义的是形参,def fun(xx):,可以给形参设置默认值,def fun(x,y='test'):,默认参数从右向左赋值。

函数调用,传得参数是实参,

函数传值,可以传入 元组和字典当作多个参数,例如

t=(x,y)

dic={x:'x',y:'y'}

fun(*t)

fun(**dic)

可以使用def fun(x,*args)*args元组的方式来接受冗余参数而不报错

    或者def fun(x,**args) **args字典的方式,接受y=xx的冗余参数

    或者def fun(x,*args,**kwargs) 可以接受任意参数

lambda匿名函数

   简短的函数定义,g = lambda  x,y : x+y

   lambda与reduce配合,reduce(lambda x,y:x*y , range(1,6))


使用字典实现switch

#!/usr/bin/pythondef add(x,y):    return x+ydef subtraction(x,y):    return x-ydef multiplication(x,y):    return x*ydef division(x,y):    return x/yoperator={"+":add,"-":subtraction,"*":multiplication,"/":division}def f(x,o,y):    return operator.get(o)(x,y)x=int(raw_input("input x: "))o=raw_input("input operator: ")y=int(raw_input("input y: "))print "%d %s %d = %d" %(x,o,y,f(x,o,y))

5、常用的内置函数

str.capitalize()  首字母大写函数

str.replace()  替换函数

str.split() 分割函数

filter() 过滤函数

zip() 

map() 


6、模块和包

目录下有__init__.py,就可以当成包。

一个py文件就可以成为一个模块。

import,import as ,from import


7、正则表达式

元字符

[] 匹配一个字符,[ab] [a-z][^a-z]

^匹配开头

$匹配结尾

\ 转意字符  

   \d 十进制数字[0-9]  \D 非十进制数字[^0-9]

   \s任何空白字符[\t\n\f\r\v]  \S任何非空白字符[^\t\n\f\r\v] 

  \w 字母数字[0-9a-zA-Z_] \W非字母数字 [^0-9a-zA-Z_]

{}表示重复几次,\d{8} 代表 重复8次\d\d\d\d\d\d\d\d\d\d

   {m,n}最少重复m次,最大重复n次。{0,}与*相同,{1,}与+相同,{0,1}与?相同

  如:  

>>> import re>>> r=r"\d{11}">>> re.findall(r,'12345678999')['12345678999']
*表示将前面的字符重复0到max次,类似于{0} {1} ... {max}

>>> r=r"1[0-9]*">>> re.findall(r,'12345678999')['12345678999']
+与*类似,但是至少出现一次

?表示匹配0次或者1次

>>> r=r"ab+">>> re.findall(r,'a')[]>>> re.findall(r,'ab')['ab']>>> re.findall(r,'abb')['abb']>>> r=r"ab?">>> re.findall(r,'a')['a']>>> re.findall(r,'ab')['ab']>>> re.findall(r,'abb')['ab']

()用来分组,findall优先显示分组中的内容,在爬虫中经常用到:

>>> email=r"\w+@\w+\.com|\.cn">>> re.findall(email,'sk@xd.com')['sk@xd.com']>>> email=r"\w+@\w+(\.com|\.cn)">>> re.findall(email,'sk@xd.com')['.com']
.* 表示匹配所有字符,a.*b匹配最长的从a到b的字符

.*? 贪婪匹配,a.*?b匹配最短的从a到b的字符


8、正则表达式的函数

(1)正则表达式的编译

对于常用的正则表达式,编译后使用可以提高效率。

>>> r1 = r"\d{3,4}-?\d{8}$">>> re_tel=re.compile(r1)>>> re_tel.findall("010-12345678")['010-12345678']>>> re_tel.findall("0571-12345678")['0571-12345678']>>> re_tel.findall("057112345678")['057112345678']
不区分大小写

>>> re_xd=re.compile(r"xd",re.I)>>> re_xd.findall('xd')['xd']>>> re_xd.findall('xD')['xD']>>> re_xd.findall('XD')['XD']>>> re_xd.findall('Xd')['Xd']
(2)re的其他函数

正则表达式的分割 re.split()

正则表达式的替换 re.sub() re.subn()
正则表达式中的匹配 re.match() ,如果匹配上了返回一个SRE.Match的对象,如果没有匹配上返回空。可以使用group(0)来获取值。

>>> import re>>> email=r"\w+@\w+(\.com|\.cn)">>> re.findall(email,'sk@xd.com')['.com']>>> re.findall(email,'sk@xd.org')[]>>> re.match(email,'sk@xd.com')<_sre.SRE_Match object at 0x7fed05a36558>>>> re.match(email,'sk@xd.cn')<_sre.SRE_Match object at 0x7fed05a36648>>>> re.match(email,'sk@xd.org')>>> re.match(email,'sk@xd.com').group(0)'sk@xd.com'

9、爬虫

用到urllib的库去获取网页源码,下载网址的图片

#!/usr/bin/pythonimport reimport urllib#获取网页源码def getHtml(url):    page = urllib.urlopen(url)    html = page.read()    return html#定义正则表达式,匹配出所有jpg网址#然后遍历网址,下载jpg文件def getimage(html):    jpg_re = r'"objURL":"(.*?\.jpg)"'    image_re = re.compile(jpg_re)    imagelist = re.findall(image_re,html)    x = 1    for imageurl in imagelist:        urllib.urlretrieve(imageurl,'%s.jpg' % x)        x+=1html = getHtml("http://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gbk&word=%D7%C0%C3%E6&hs=0&fr=ala&ori_query=%E6%A1%8C%E9%9D%A2&ala=0&alatpl=sp&pos=0")getimage(html)

10、内存操作 之 赋值、浅拷贝、深拷贝

赋值:引用 

    a = b

浅拷贝:外层对象拷贝,内层对象引用

    b = copy.copy(a)  拷贝函数

    b = a[:]   切片

    b = list(a)   重新创建对象

深拷贝:外层和内层对象都是拷贝

    b = copy.deepcopy(a)

>>> import copy>>> a = [1,2,3,['a','b','c']]>>> b = a>>> c = a[:]>>> d = list(a)>>> e = copy.copy(a)>>> f = copy.deepcopy(a)>>> id(a),id(b),id(c),id(d),id(e),id(f)(140376746125648,  140376746125648,  140376746204480,  140376746204768,  140376746204840,  140376746204408)>>> id(a[3]),id(b[3]),id(c[3]),id(d[3]),id(e[3]),id(f[3])(140376746125720,  140376746125720,  140376746125720,  140376746125720,  140376746125720,  140376746204552)>>> a,b,c,d,e,f([1, 2, 3, ['a', 'b', 'c']],  [1, 2, 3, ['a', 'b', 'c']],  [1, 2, 3, ['a', 'b', 'c']],  [1, 2, 3, ['a', 'b', 'c']],  [1, 2, 3, ['a', 'b', 'c']],  [1, 2, 3, ['a', 'b', 'c']])>>> a.append('d')>>> a,b,c,d,e,f([1, 2, 3, ['a', 'b', 'c'], 'd'],  [1, 2, 3, ['a', 'b', 'c'], 'd'],  [1, 2, 3, ['a', 'b', 'c']],  [1, 2, 3, ['a', 'b', 'c']],  [1, 2, 3, ['a', 'b', 'c']],  [1, 2, 3, ['a', 'b', 'c']])>>> a[3].append('d')>>> a,b,c,d,e,f([1, 2, 3, ['a', 'b', 'c', 'd'], 'd'],  [1, 2, 3, ['a', 'b', 'c', 'd'], 'd'],  [1, 2, 3, ['a', 'b', 'c', 'd']],  [1, 2, 3, ['a', 'b', 'c', 'd']],  [1, 2, 3, ['a', 'b', 'c', 'd']],  [1, 2, 3, ['a', 'b', 'c']])

11、文件的读写操作

r 只读

r+ 读写

w 写文件,如果没有文件新创建文件

w+ 读写文件,如果没有文件新创建文件

a  写文件,追加写入,没有文件新建

a+ 读写文件,追加写入,没有文件新建

b 二进制打开

U 支持换行符

>>> fnew=open('new.txt','w+')>>> fnew.write('hello new file')>>> fnew.close()

12、文件的其他函数




0 0
原创粉丝点击