python备忘

来源:互联网 发布:杨宪怎么死的 知乎 编辑:程序博客网 时间:2024/05/29 17:57

python中有许多提高效率的方法和技巧,总结下来

python中不同对象的转换

int(x [,base ])         将x转换为一个整数  long(x [,base ])        将x转换为一个长整数  float(x )               将x转换到一个浮点数  complex(real [,imag ])  创建一个复数  str(x )                 将对象 x 转换为字符串  repr(x )                将对象 x 转换为表达式字符串  eval(str )              用来计算在字符串中的有效Python表达式,并返回一个对象  tuple(s )               将序列 s 转换为一个元组  list(s )                将序列 s 转换为一个列表  chr(x )                 将一个整数转换为一个字符  unichr(x )              将一个整数转换为Unicode字符  ord(x )                 将一个字符转换为它的整数值  hex(x )                 将一个整数转换为一个十六进制字符串  oct(x )                 将一个整数转换为一个八进制字符串  b = '%x' % a            使用hex转换一个整数会出现0x头和L尾,而这么写可以直接得到数据格式化的字符串     

python中的日期处理

得到当前时间的格式化字符串 datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S');
从字符串转为日期 time.strptime('2006-1-2', "%Y-%m-%d")
计算时间差 starttime = datetime.datetime.now()endtime = datetime.datetime.now()print (endtime - starttime).seconds
计算时间加减时间差之后的时间 d1 = datetime.datetime.now()d3 = d1 + datetime.timedelta(days =10)


python中的字符串处理

trim,字符是可以定制的 s.strip() s.lstrip() s.rstrip()' ab ,'.strip(',')
比较字符串要用,不能用==cmp(sStr1,sStr2)
查找字符串,两者区别在于找不到时find返回-1,而index就异常了str1.index(str2)str1.find(str2)
字符串替换a.replace(str1, str2)
字符串分割str1.split(str2)
索引取子串 s[0:5]字符串翻转 a[::-1]
连接列表为数组a = ['a','b','c','d']''.join(a)
字符串拼接astr = 'i love %s' % mastr = "i love {python}".format(python=m)astr = "i love %(python)s " % {'python':m}"%.2f" % 50.4625
字符串大小写str.upper() str.lower() str.capitalize() str.istitle()

序列可以相乘或相加"ab" * 10['a', 'b'] + [1, 2]
指针拷贝 y = x值拷贝 y = x[:]

python中的文件处理

对文件名的操作

os.path.split(r"c:\python\hello.py") --> ("c:\\python", "hello.py")       分离文件名os.path.basename(r"r:\python\hello.py") --> "hello.py"                    获取文件名os.path.splitext(r"c:\python\hello.py") --> ("c:\\python\\hello", ".py")  分离扩展名os.path.dirname(r"c:\python\hello.py") --> "c:\\python"                   获取路径名
对文件的操作
os.mknod("test.txt")                   touch一个文件shutil.copyfile("oldfile","newfile")   复制文件shutil.move("oldpos","newpos")         剪切文件os.remove("file")                      删除文件os.path.isfile(file)                   判断是否是文件os.rename("oldname","newname")         重命名os.chmod(file)                         修改文件权限os.stat(file)                          获取文件属性os.path.getsize(filename)              获取文件大小os.path.walk()                         获得目录下所有文件os.path.join(path, name)               连接目录与文件os.path.isdir(file)                    判断是否是目录os.path.islink(file)                   判断是否链接文件os.path.isabs("file")                  判断是否绝对路径os.path.exists(file)                   判断路径是否存在

fp = open("test.txt",w)fp.read([size])fp.readline([size])fp.readlines([size])fp.write(str)fp.writelines(seq)fp.flush()fp.seek(offset[,whence])fp.truncate([size])fp.next()

对目录的操作
os.mkdir("file")                       创建目录os.makedirs(r"c:\python \test")        创建多级目录os.rmdir("dir")                        删除目录os.removedirs(r"c:\python")           删除多个目录shutil.rmtree("dir")                   强制删除os.getcwd()                            得到当前工作目录os.listdir()                           得到指定目录下的所有文件和目录os.chdir("path")                       改变当前工作目录shutil.copytree("olddir","newdir")     复制目录,且newdir必须不存在

列表的方法(tuple无方法!)

append, count, extend, index, insert, pop, remove, reverse, sort, sorted
lst.sort(key=len,reverse=True)

(x, y, z) = ('a', 'b', 'c')(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)


Python内置的几个重要操作zip, map, reduce, filter

zip

a = [1,2,3]b = [4,5,6]zipped = zip(a,b)#[(1, 4), (2, 5), (3, 6)]zip(*zipped)#[(1, 2, 3), (4, 5, 6)]
map,用function对iterable中的每个元素计算,并返回计算结果列表,这里的iterable仅仅是function的参数。lambda

map(function, iterable...)a = [1, 2, 3, 4, 5]b = [2, 2, 9, 0, 9]map(max, a, b)#求两数组最大值map(lambda pair: max(pair), zip(a, b))#求两数组最大值的另一种方式

reduce,function每次只传入两个数据,第一次会将iterable中第1,2个数据传入;第二次以后都以上次计算结果作为参数1,iterable的下一个数据作为参数2

reduce(function, iterable...)reduce(lambda x,y:x*y,range(1,3),5)#1*2*5

filter,用function对iterable做计算,用结果的boolean值来判断是否需要过滤iterable中的数据

filter(function, iterable)filter(lambda x : not x%2,range(10))

可以同过滤器表达式比较

[mapping-expression for element in source-list if filter-expression]";".join(["%s=%s" % (k, v) for k, v in params.items()])methodList = [method for method in dir(object) if callable(getattr(object, method))]<span style="font-family:Arial, Helvetica, sans-serif;"><span style="white-space: normal;"></span></span>


python反射的核心getattr(),这是一个神级方法,可以作用于任何对象,就像java中反射以Class为核心,而c#中以Type为核心一样

getattr(li, "append")("Moe")


如果要删除python字典,有两个方法,即内置方法 del和字典的方法pop。

其中del这个方法有陷阱,需要注意

binfo = {'name':'jay','age':20,'python':'haha'}x = binfo['name']del xprint binfodel binfo['name']print binfo

上面一段程序,输出是:

{'python': 'haha', 'age': 20, 'name': 'jay'}{'python': 'haha', 'age': 20}
可以看出来del并非直接是根据value来删除字典中元素的,因为单纯给他一个value是不能找到要删哪个元素的,而del binfo['name']才给他了足够多的元素,一个是这个字典对象,另一个是该字典的key。

链式操作符

x=5x < 10 < x*7 < 100(1 and [a] or [b])[0]


python中一些库安装

easy_install的安装:https://pypi.python.org/pypi/setuptools#downloads,下载之后直接执行就好了,目的是在python目录下生成一个scripts文件夹,从而可以直接调用easy_install这个程序。

在调用过程中可能出错如下:UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 1: ordinal not in range(128) 原因是注册表可能为gbk格式。

解决办法是:到python目录下的lib中找到mimetypes.py

default_encoding = sys.getdefaultencoding()改为if sys.getdefaultencoding() != 'gbk':     reload(sys)     sys.setdefaultencoding('gbk')default_encoding = sys.getdefaultencoding()

pip安装:到这里下载 https://raw.githubusercontent.com/pypa/pip/master/contrib/get-pip.py,然后直接执行就好了

python未注册,报错如下:python version 2.7 required which was not found in the registry,原因是python没进注册表。

解决办法:新建程序regist.py,然后执行,则将python放入注册表

import sys  from _winreg import *  # tweak as necessaryversion = sys.version[:3]installpath = sys.prefix  regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)installkey = "InstallPath"pythonkey = "PythonPath"pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (    installpath, installpath, installpath)  def RegisterPy():    try:        reg = OpenKey(HKEY_CURRENT_USER, regpath)    except EnvironmentError as e:        try:            reg = CreateKey(HKEY_CURRENT_USER, regpath)            SetValue(reg, installkey, REG_SZ, installpath)            SetValue(reg, pythonkey, REG_SZ, pythonpath)            CloseKey(reg)        except:            print "*** Unable to register!"            return        print "--- Python", version, "is now registered!"        return    if (QueryValue(reg, installkey) == installpath and        QueryValue(reg, pythonkey) == pythonpath):        CloseKey(reg)        print "=== Python", version, "is already registered!"        return    CloseKey(reg)    print "*** Unable to register!"    print "*** You probably have another Python installation!"    if __name__ == "__main__":    RegisterPy()

lxml的安装:lxml是解析xml和html的好工具,windows下安装lxml很简单,可以到这里https://pypi.python.org/pypi/lxml/2.3直接下载exe程序

linux下的lxml稍微麻烦点,如果是ubuntu,使用如下一堆命令,命令很简单,不解释。

apt-get updateapt-cache search lxml apt-cache show python-lxmlapt-get install python-lxml
pip同样可以安装

pip install lxml

pyquery的安装:下载源码http://pypi.python.org/pypi/pyquery,执行

python setup.py buildpython setup.py install

twisted的安装:windows下载msi直接安装http://twistedmatrix.com/trac/wiki/Downloads

linux下可以如下几种方式

pip方式,首先要执行这个,把开发环境装好

apt-get install build-essential python-dev
接下来可以直接安装,它会顺带把依赖的zope装好

pip install Twisted==14.0
直接编译源码,先到https://pypi.python.org/找到合适的版本下载,然后执行
python setup.py buildpython setup.py install

zope的安装:下载相应的zope https://pypi.python.org/pypi/zope.interface#download

chardet的安装:下载chardet源码 https://pypi.python.org/pypi/chardet#downloads,执行

python setup.py buildpython setup.py install
mysql-python的安装:下载exe直接安装 https://pypi.python.org/pypi/MySQL-python/1.2.5

linux下用pip安装

pip install mysql-python==1.2.5
mysql有可能报如下错:ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)-mysql.sock

导致该错误原因很多,在linux下的一个经典原因就是需要把连接的localhost换成127.0.0.1,号称这是通过localhost的tcp请求导致了unix socket错误。

其他一些错误原因可以参考这里:

http://blog.csdn.net/leisure512/article/details/5139104

http://chinacheng.iteye.com/blog/1100999


python的隐藏特性 https://pyzh.readthedocs.org/en/latest/python-hidden-features.html

                                 http://blog.csdn.net/zhzhl202/article/details/7524609
python的zip, map和lambda https://bradmontgomery.net/blog/2013/04/01/pythons-zip-map-and-lambda/
Python字符编码详解 http://www.cnblogs.com/huxi/archive/2010/12/05/1897271.html
python字符串操作-老王的博客:http://www.cnpythoner.com/wiki/string.html
dive into python: http://woodpecker.org.cn/diveintopython/index.html
python bit操作:http://wiki.python.org/moin/BitManipulation
python内置操作:http://www.cnblogs.com/flyingfish/archive/2007/05/16/748123.html
Python开发者应该知道的7个开发库 http://developer.51cto.com/art/201211/364737.htm
Python项目自动化部署最佳实践 http://www.the5fire.com/auto-deploy-tool-for-python-app.html
python时间 http://www.sharejs.com/codes/python/8664
http://www.crifan.com/python_re_sub_detailed_introduction/
http://www.coder4.com/archives/3711
http://www.cnblogs.com/moinmoin/archive/2011/02/28/bin_oct_int_hex.html


原创粉丝点击