您的位置:首页 > 编程语言 > Python开发

python学习笔记

2015-11-29 20:26 639 查看
队列:先进先出

list = ["apple", "banana", "grape"]

list.append("orange")

print list

print "Pop:",list.pop(0)

print list

堆栈:先进后出

list = ["apple", "banana", "grape"]

list.append("orange")

print list

print "Pop:",list.pop()

print list

2. 切片

#! /usr/bin/env python

#coding=utf-8

tuple = ("apple", "banana", "grape", "orange")

print tuple[:3] #取开头到第三个元素

print tuple[3:] #取第四个元素到最后一个元素

print tuple[0, -1] #整个数组删除最后一个元素

3. 合并

zip函数接受任意多个序列作为参数,将所有序列按相同的索引组合成一个元素是各个序列合并成的tuple的新序列,新的序列的长度以参数中最短的序列为准。另外(*)操作符与zip函数配合可以实现与zip相反的功能,即将合并的序列拆成多个tuple。

①tuple的新序列

>>>>x=[1,2,3],y=['a','b','c']

>>>zip(x,y)

[(1,'a'),(2,'b'),(3,'c')]

②新的序列的长度以参数中最短的序列为准.

>>>>x=[1,2],y=['a','b','c']

>>>zip(x,y)

[(1,'a'),(2,'b')]

③(*)操作符与zip函数配合可以实现与zip相反的功能,即将合并的序列拆成多个tuple。

>>>>x=[1,2,3],y=['a','b','c']

>>>>zip(*zip(x,y))

[(1,2,3),('a','b','c')]

4. 定义常量

在Python中没有提供定义常量的保留字,需要自己定义一个常量类来实现常量的功能!在此提供《Python Cookbook》一书中定义的常量模块const,代码如下:

说明:此类是定义了一个方法__setattr__()和一个异常类型ConstError,主要是判断定义的常量是否在字典中,在则抛出异常,否则,给新创建的常量赋值

[python] view
plaincopyprint?

class _const:

class ConstError(TypeError):pass

def __setattr__(self,name,value):

if self.__dict__.has_key(name):

raise self.ConstError,"Can't rebind const (%s)"% name

self.__dict__[name]=value

import sys

sys.modules[__name__]=_const()

5.range

http://hi.baidu.com/life_to_you/item/b31c8db8ba467fe84ec7fd04

print range(1, 5)

输出1,2,3,4

print range(1,5,1)

输出1234

print range(1,5,2)

输出1,3

print range(0,5,2)

输出0,2,4

6.正则表达式

import re

s = "HELLO WOLRD"

print re.findall(r"^hello", s, re.IGNORECASE)

7. 读取文件

#读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式

rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)

w 以写方式打开,

a 以追加模式打开 (从 EOF 开始, 必要时创建新文件)

r+ 以读写模式打开

w+ 以读写模式打开 (参见 w )

a+ 以读写模式打开 (参见 a )

rb 以二进制读模式打开

wb 以二进制写模式打开 (参见 w )

ab 以二进制追加模式打开 (参见 a )

rb+ 以二进制读写模式打开 (参见 r+ )

wb+ 以二进制读写模式打开 (参见 w+ )

ab+ 以二进制读写模式打开 (参见 a+ )

f = file("hello.txt", "w+")

li = ["Sexy boy\n", "test\n"]

f.writelines(li)

f.close()

f = file("hello.txt", "a+")

new_context = "goodbye"

f.write(new_context)

f.close

文件删除

import os

file("hello.txt", "w")

if os.path.exists("hello.txt"):

os.remove("hello.txt")

os.path.split(path)

将path分割成目录和文件名二元组返回。

>>> os.path.split('c:\\csv\\test.csv')

('c:\\csv', 'test.csv')

>>> os.path.split('c:\\csv\\')

('c:\\csv', '')

os.path.join(path1[, path2[, ...]])

将多个路径组合后返回,第一个绝对路径之前的参数将被忽略。

>>> os.path.join('c:\\', 'csv', 'test.csv')

'c:\\csv\\test.csv'

>>> os.path.join('windows\temp', 'c:\\', 'csv', 'test.csv')

'c:\\csv\\test.csv'

>>> os.path.join('/home/aa','/home/aa/bb','/home/aa/bb/c')

'/home/aa/bb/c'

8.批量修改文件名

import shutil

import os

files = os.listdir(".")

for filename in files:

pos = filename.find(".")

if filename[pos + 1:] == "html":

newname = filename[:pos + 1] + "htm"

os.rename(filename,newname)

files = os.listdir(".")

for filename in files:

li = os.path.splitext(filename)

if li[1] == ".html":

newname = li[0] + ".htm"

os.rename(filename, newname)

9. 在文件中查找内容

#!/usr/bin/python

# -*- coding: UTF-8 -*-

import shutil

import os

import re

f1 = file("hello.txt", "r")

count = 0

for s in f1.readlines():

li = re.findall("test", s)

if len(li) > 0:

count = count + li.count("test")

print "find " + str(count) + " test"

10.读取配置文件

import ConfigParser

config = ConfigParser.ConfigParser()

config.read(“ODBC.ini”)

#获取配置块

config.sections()

#获取配置项

config.options()

#获取配置内容

config.iteams()

#根据配置快和配置项返回内容

config.get()

写入配置文件

添加配置快

config.add_section()

设置配置项和配置内容

config.set

修改配置项和配置内容

config.set()

删除配置文件

删除配置项

remove_options

删除配置块

remove_section

11.目录的添加删除操作

import os

os.mkdir("hello")

os.rmdir("hello")

os.makedirs("hello/world")

os.removedirs("hello/world")

12. 目录的遍历

#!/usr/bin/python

# -*- coding: UTF-8 -*-

import os

def VisitDir(path):

li = os.listdir(path)

for p in li:

pathname = os.path.join(path, p)

if not os.path.isfile(pathname):

VisitDir(pathname)

else:

print pathname

if __name__ == "__main__":

path = r"C:\windows"

VisitDir(path)

13. 文件流(输出流 输出到文件)

import sys

sys.stdout = open(r"./hello.txt", "a")

print "\ngoodbye\n"

sys.stdout.close()

输入流读取文件输入到屏幕设备上

import sys

sys.stdin = open(r"./hello.txt", "r")

for line in sys.stdin.readlines():

print line

14. 类

定义私有变量用__定义

class Fruit:

def __init__(self):

self.__color = "red" #私有属性定义__

15. 私有变量访问方式

print _Fruit__color

16.抽象类使用

def abstract():

raise NotImplementedError("abstract")

class Fruit:

def __init__(self):

if self.__class__ is Fruit:

abstract()

print "Fruit"

class Apple(Fruit):

def __init__(self):

Fruit.__init__(self)

print "Apple"

if __name__ == "__main__":

apple = Apple();

17.多态性

#!/usr/bin/python

# -*- coding: UTF-8 -*-

class Fruit:

def __init__(self, color = None):

self.color = color

class Apple(Fruit):

def __init__(self, color = "red"):

Fruit.__init__(self,color)

class Banana(Fruit):

def __init__(self, color = "yellow"):

Fruit.__init__(self,color)

class FruitShop:

def sellFruit(self, fruit):

if isinstance(fruit, Apple):

print "sell apple"

if __name__ == "__main__":

shop = FruitShop()

apple = Apple("red")

banana = Banana("yellow")

shop.sellFruit(apple)

shop.sellFruit(banana)

18. python解析HTML

#! /usr/bin/env python

#coding=utf-8

import BeautifulSoup

import urllib2

page = urllib2.urlopen("http://www.baidu.com/index.html")

soup = BeautifulSoup.BeautifulSoup(page)

print soup

输出

> "C:\Python27\pythonw.exe" -u "C:\Users\Administrator\Desktop\python\pachong\pa.py"

<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><title>\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b\xef\xbc\x8c\xe4\xbd\xa0\xe5\xb0\xb1\xe7\x9f\xa5\xe9\x81\x93 </title><style>html,body{height:100%;}html{overflow-y:auto}#wrapper{position:relative;_position:;min-height:100%}#content{padding-bottom:100px;text-align:center;}#ftCon{height:100px;position:absolute;bottom:44px;text-align:center;width:100%;margin:0
auto;z-index:0;overflow:hidden;}#ftConw{width:720px;margin:0 auto;}body{font:12px arial;text-align:;background:#fff}body,p,form,ul,li{margin:0;padding:0;list-style:none}body,form,#fm{position:relative}td{text-align:left}img{border:0}a{color:#00c}a:active{color:#f60}#u{color:#999;padding:4px
10px 5px 0;text-align:right}#u a{margin:0 5px}#u .reg{margin:0}#m{width:720px;margin:0 auto;}#nv a,#nv b,.btn,#lk{font-size:14px}#fm{padding-left:110px;text-align:left;z-index:1;}input{border:0;padding:0}#nv{height:19px;font-size:16px;margin:0 0 4px;text-align:left;text-indent:137px;}.s_ipt_wr{width:418px;height:30px;display:inline-block;margin-right:5px;background:url(http://s1.bdstatic.com/r/www/img/i-1.0.0.png)
no-repeat -304px 0;border:1px solid #b6b6b6;border-color:#9a9a9a #cdcdcd #cdcdcd #9a9a9a;vertical-align:top}.s_ipt{width:405px;height:22px;font:16px/22px arial;margin:5px 0 0 7px;background:#fff;outline:none;-webkit-appearance:none}.s_btn{width:95px;height:32px;padding-top:2px\9;font-size:14px;background:#ddd
url(http://s1.bdstatic.com/r/www/img/i-1.0.0.png);cursor:pointer}.s_btn_h{background-position:-100px 0}.s_btn_wr{width:97px;height:34px;display:inline-block;background:url(http://s1.bdstatic.com/r/www/img/i-1.0.0.png)
no-repeat -202px 0;*position:relative;z-index:0;vertical-align:top}#lg img{vertical-align:top;margin-bottom:3px}#lk{margin:33px 0}#lk span{font:14px "\xe5\xae\x8b\xe4\xbd\x93"}#lm{height:60px}#lh{margin:16px 0 5px;word-spacing:3px}.tools{position:absolute;top:-4px;*top:10px;right:7px;}#mHolder{width:62px;position:relative;z-index:296;display:none}#mCon{height:18px;line-height:18px;position:absolute;cursor:pointer;padding:0
18px 0 0;background:url(http://s1.bdstatic.com/r/www/img/bg-1.0.0.gif) no-repeat right -134px;background-position:right -136px\9}#mCon
span{color:#00c;cursor:default;display:block}#mCon .hw{text-decoration:underline;cursor:pointer}#mMenu a{width:100%;height:100%;display:block;line-height:22px;text-indent:6px;text-decoration:none;filter:none\9}#mMenu,#user ul{box-shadow:1px 1px 2px #ccc;-moz-box-shadow:1px
1px 2px #ccc;-webkit-box-shadow:1px 1px 2px #ccc;filter: progid:DXImageTransform.Microsoft.Shadow(Strength=2, Direction=135, Color="#cccccc")\9;}#mMenu{width:56px;border:1px solid #9b9b9b;list-style:none;position:absolute;right:27px;top:28px;display:none;background:#fff}#mMenu
a:hover{background:#ebebeb}#mMenu .ln{height:1px;background:#ebebeb;overflow:hidden;font-size:1px;line-height:1px;margin-top:-1px}#cp,#cp a{color:#666666;}#seth{display:none;behavior:url(#default#homepage)}#setf{display:none;}#sekj{margin-left:14px;}</style>

<script type="text/javascript">function h(obj){obj.style.behavior='url(#default#homepage)';var a = obj.setHomePage('http://www.baidu.com/');}</script></head>

<body><div id="wrapper"><div id="content">

<div id="ie6tipcon"></div>

<div id="u"><a href="http://www.baidu.com/gaoji/preferences.html" name="tj_setting">\xe6\x90\x9c\xe7\xb4\xa2\xe8\xae\xbe\xe7\xbd\xae</a>|<a
href="https://passport.baidu.com/v2/?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" name="tj_login"
id="lb" onclick="return false;">\xe7\x99\xbb\xe5\xbd\x95</a><a href="https://passport.baidu.com/v2/?reg&regType=1&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F"
target="_blank" name="tj_reg" class="reg">\xe6\xb3\xa8\xe5\x86\x8c</a></div>

<div id="m"><p id="lg"><img src="http://www.baidu.com/img/baidu_sylogo1.gif" width="270" height="129" /></p>

<p id="nv"><a href="http://news.baidu.com">\xe6\x96\xb0 \xe9\x97\xbb</a>\xe3\x80\x80<b>\xe7\xbd\x91 \xe9\xa1\xb5</b>\xe3\x80\x80<ahref="http://tieba.baidu.com">\xe8\xb4\xb4 \xe5\x90\xa7</a>\xe3\x80\x80<ahref="http://zhidao.baidu.com">\xe7\x9f\xa5 \xe9\x81\x93</a>\xe3\x80\x80<ahref="http://music.baidu.com">\xe9\x9f\xb3 \xe4\xb9\x90</a>\xe3\x80\x80<ahref="http://image.baidu.com">\xe5\x9b\xbe \xe7\x89\x87</a>\xe3\x80\x80<ahref="http://video.baidu.com">\xe8\xa7\x86 \xe9\xa2\x91</a>\xe3\x80\x80<a href="http://map.baidu.com">\xe5\x9c\xb0 \xe5\x9b\xbe</a></p><div id="fm"><form
name="f" action="/s"><span class="s_ipt_wr"><input type="text" name="wd" id="kw" maxlength="100" class="s_ipt" /></span><input type="hidden" name="rsv_bp" value="0" /><input type="hidden" name="rsv_spt" value="3" /><span class="s_btn_wr"><input type="submit"
value="\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b" id="su" class="s_btn" onmousedown="this.className='s_btn s_btn_h'" onmouseout="this.className='s_btn'" /></span></form><span class="tools"><span id="mHolder"><div id="mCon"><span>\xe8\xbe\x93\xe5\x85\xa5\xe6\xb3\x95</span></div></span></span><ul
id="mMenu"><li><a href="#" name="ime_hw">\xe6\x89\x8b\xe5\x86\x99</a></li><li><a href="#" name="ime_py">\xe6\x8b\xbc\xe9\x9f\xb3</a></li><li class="ln"></li><li><a href="#" name="ime_cl">\xe5\x85\xb3\xe9\x97\xad</a></li></ul></div>

<p id="lk"><a href="http://baike.baidu.com">\xe7\x99\xbe\xe7\xa7\x91</a>\xe3\x80\x80<ahref="http://wenku.baidu.com">\xe6\x96\x87\xe5\xba\x93</a>\xe3\x80\x80<a href="http://www.hao123.com">hao123</a><span>
| <a href="http://www.baidu.com/more/">\xe6\x9b\xb4\xe5\xa4\x9a>></a></span></p><p id="lm"></p>

</div></div><div id="ftCon"><div id="ftConw"><p><a id="seth" onclick="h(this)" href="/" onmousedown="return ns_c({'fm':'behs','tab':'homepage','pos':0})">\xe6\x8a\x8a\xe7\x99\xbe\xe5\xba\xa6\xe8\xae\xbe\xe4\xb8\xba\xe4\xb8\xbb\xe9\xa1\xb5</a><a id="setf" href="http://www.baidu.com/cache/sethelp/index.html"
onmousedown="return ns_c({'fm':'behs','tab':'favorites','pos':0})" target="_blank">\xe6\x8a\x8a\xe7\x99\xbe\xe5\xba\xa6\xe8\xae\xbe\xe4\xb8\xba\xe4\xb8\xbb\xe9\xa1\xb5</a><span id="sekj"><a href="http://www.baidu.com/search/baidukuaijie_mp.html"
target="_blank" onmousedown="return ns_c({'fm':'behs','tab':'kuaijie','pos':1})">\xe6\x8a\x8a\xe7\x99\xbe\xe5\xba\xa6\xe6\xb7\xbb\xe5\x8a\xa0\xe5\x88\xb0\xe6\xa1\x8c\xe9\x9d\xa2</a></span></p><p id="lh"><a href="http://e.baidu.com/?refer=888"
onmousedown="return ns_c({'fm':'behs','tab':'btlink','pos':2})">\xe5\x8a\xa0\xe5\x85\xa5\xe7\x99\xbe\xe5\xba\xa6\xe6\x8e\xa8\xe5\xb9\xbf</a> | <a href="http://top.baidu.com">\xe6\x90\x9c\xe7\xb4\xa2\xe9\xa3\x8e\xe4\xba\x91\xe6\xa6\x9c</a>
| <a href="http://home.baidu.com">\xe5\x85\xb3\xe4\xba\x8e\xe7\x99\xbe\xe5\xba\xa6</a> | <a href="http://ir.baidu.com">About Baidu</a></p><p
id="cp">©2013 Baidu <a href="/duty/">\xe4\xbd\xbf\xe7\x94\xa8\xe7\x99\xbe\xe5\xba\xa6\xe5\x89\x8d\xe5\xbf\x85\xe8\xaf\xbb</a> <a href="http://www.miibeian.gov.cn"
target="_blank">\xe4\xba\xacICP\xe8\xaf\x81030173\xe5\x8f\xb7</a> <img src="http://www.baidu.com/cache/global/img/gs.gif" /></p></div></div>

</div></body>

<script>var bds={se:{},comm : {ishome : 1,sid : "1758",user : "",username : "",sugHost : "http://suggestion.baidu.com/su",loginAction :
[]}}</script><script type="text/javascript" src="http://s1.bdstatic.com/r/www/cache/global/js/tangram-1.3.4c1.0.js"></script><script type="text/javascript"
src="http://s1.bdstatic.com/r/www/cache/user/js/u-1.3.4.js"></script>

</html>

<!--640015f8e5e79ae7-->
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: