python 开发文档镇楼。 https://docs.python.org/2/index.html
关于代码
python的合理布局
(1)起始行
(2) 模块文档
(3)模块导入
(4)变量定义
(5)类定义
(6)函数定义
(7)主程序
文档编码
#encoding: utf-8 # 设置系统编码
import codecs
codecs.open("loc,txt","w","utf-8")
模块的测试
if __name__=="__main__":
test()
系统参数
import sys
sys.argv #argv是一个数组
#你在命令行输入
#>python thisfile.py
#会得到一个元素的数组,数组里面的元素是thisfile.py
python的重定向
import sys
print>>sys.stderr,'error'
logfile=open('a.txt','w')
print>>logfile,'ssss'
logfile.close()
在刚开始的时候命令行输出流重新定向
$ python code.py >>save.txt
时间的显示
import time
time.strftime("%X",time.localtime()) #显示当前时间
import time
t0=time.time()
t1 = time.time()
print(" %.2g sec" % (t1 - t0)) #显示运行时间
基础语法
变量名
python的下划线
XX 表示是系统自带的变量
_XX 表示是类中的私有变量
输入
user=raw_input('enter')
print 'your enter',user
输出
pretty print 冲着这个名字也要用一下啊
https://docs.python.org/2/library/pprint.html
>>> import pprint
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
>>> stuff.insert(0, stuff[:])
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(stuff)
[ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
'spam',
'eggs',
'lumberjack',
'knights',
'ni']
>>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
... ('parrot', ('fresh fruit',))))))))
>>> pp = pprint.PrettyPrinter(depth=6)
>>> pp.pprint(tup)
('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
indent代表打印的缩进,depth代表输出的深度,还有一个宽度 width代表打印出来的数据的项
位运算
异或 ^
循环
for循环,如果是递增的变量的话
for i in range(3):
print i
range是生成一个list,当n很大的时候,那么占用内存会很大
xrange占用内存比起来range小,所以平时可以尽量选择xrange,用法是一样的。
for i in xrange(3):
print i
以前我都是额外计数的,后来发现用enumerate好很多。 然后,它的效率比较低,所以循环比较多的时候还是建议自己算。
for i,ele in enumerate(open(ff)):
print i,ele
迭代器
数据结构
list
https://docs.python.org/2/library/stdtypes.html#typesseq
list 中括号来表示
list=[]
list.append("a")
list的查找和删除
in可以判读元素是否存在
onewords=[111,222,333]
print 111 in onewords
print onewords.remove(111)
print 111 in onewords
list的扩充,la扩充lb
la.extend(lb)
list 排序
list.sort()
反序
list.sort(reverse=True)
删除某个元素
list.pop()
#最后一个元素
list.pop(0)
#第一个元素
list.pop(i)
#序列为i的元素
http://www.jb51.net/article/52730.htm
dict
字典用{}来表示
dic={}
if "a" in dic:
dic["a"]+=1
else:
dic["a"]=1
print dic
想要获取字典长度
len(dic)
字典的排序
字典本身是无序的,然而有时候要进行排序的时候,先生成set,然后再利用sorted进行排序
https://wiki.python.org/moin/HowTo/Sorting
d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
sorted(d.items(), key=lambda t: t[0])
元组
元组用()来表示,元组本身不可以更改
python实现两个变量交换,其实就是生成了元组
x,y=1,2
x,y=y,x
字符串
python的编码问题,
一本书里面说python有三种字符串,(str),unicode,basestring三类。
编码本身分为三种方式,系统编码,文件编码,python编码,系统编码是代码的编码 a=”哈哈” ,python编码是运行的时候 输出的时候 print a ,文件编码是文件的编码
文件保存设置系统编码
字符串整个是一个地址,是常量,如果字符串进行改变,那么肯定是生成一个新的串,然后把旧的串删除。
字符串的切片 (切片的操作不要老放在循环里面)
str[0:-1]
#从字符串开始到最后倒数第二个
字符串的连接
string.upper(a[0:3]+a[20])
虽然加号就能连接,但是python要为每个参加连接操作的字符串分配新的内存,所以推荐用%
、
'%s %s' %('spa','Inq')
' '.join(('ss','aa','bb'))
#ss aa bb
如果是某个字符串自己和自己重复连接
'a'*10
#aaaaaaaaaa
字符串的替代
string.replace(str1,str2,num=string count(str1))
#把str1替换成str2,如果num存在,则不超过num次
字符串转数字,
int(str)
字符串的查找
'bc' in 'abcd'
'n' not in 'abcd'
#还有find 和index
python string模块自定义的字符串
import string
string.uppercase #大写
string.lowercase #小写
string.letters#大小写
string.digits #数字
字符串的替代,清理标点符号, unicode清理,
not_letters_or_digits = u'!"#%\'()*+,-./:;<=>?@[\]^_`{|}~'
translate_table=dict((ord(char),u' ') for char in not_letters_or_digits)
line=unicode(line).translate(translate_table)
面向对象
python 类,有时候有称为类对象。实例 Instance
class MyData(object):
pass
mathObj=MyData()
mathObj.x=3
文件读取
json文件
http://www.cnblogs.com/coser/archive/2011/12/14/2287739.html
python的json和js的json不一样。
文件读取
savefile=open("read.txt",'r')
logfile=open('an.json','w')
fjson=open("s.json","w")
f.write(json.dump(data))
f.close()
这里建议读取文件指定读入流。为了防止乱码什么的,最好统一用utf-8编码。现在基本是用codecs读文件了。
import codecs
codecs.open("filename.txt","r","utf-8")
codecs.open("filename.txt","w",utf-8")
如果的是json格式的话,那么
数据的序列化和反序列化
pickle存储数据,也就是对象序列化,可以把运行中的对象存储在本地。
save_file = "save.pk"
with open(save_file, 'w') as f:
pickle.dump(WMD_D, f)
#WMD_D是要存储的对象
读取数据,也就是反序列化。
import pickle
load_file = "save.pk"
with open(load_file) as f:
objectA= pickle.load(f)
json
path="" #file path
for line in open(path):
rec=json.loads(line)
py数据库
http://blog.youkuaiyun.com/artemisrj/article/details/43371263
异常
现在的理解是异常能够让我的程序在不跳出的时候运行,而且记录相应的错误,可以存在文件里面当作日志。这个在执行数据量大的时候,可以用来忽略一些小的错误。
try:
cur.execute('select words from '+review_bui[0])
#pdb.set_trace()
except Exception,e:
nots.write(str(e)+'\n')
python 模块
系统路径‘
sys.path.append(‘F:\code\yelp2\subpython’) 加进去就是系统的路径了
python库收集
http://blog.youkuaiyun.com/artemisrj/article/details/50813682
其他
调试工具
http://segmentfault.com/a/1190000000356018
python的一些问题以及处理思路
http://blog.youkuaiyun.com/artemisrj/article/details/49535433
关键字查看的函数 iskeyword()
python不支持重载
可以输入 import this ,是python 之禅
测试模块 unittest ,有时候被叫做 Pyunit
python核心编程 课后习题
2-5(b)
num=[ x for x in range(11)]
for i in num:
print i
2-6 条件判断,记得转化为int
x=int(raw_input('put the num:'))
if x==0:
print 'zero'
elif x>0:
print 'positive'
else:
print 'negative'
2-7 循环和字串
str=raw_input('put the string:')
for c in str:
print c
字符串,分为普通字符串和unicode字符串,后者要加u, ‘str’ , u’str’
2-10
print('Enter')
v=[]
i=0
s=0
while s==0:
a=input('n%d=' % (i+1))
if 0<a<=100:
break
else:
continue
print('end')