python编程书写技巧_python编程技巧

python编程中常用的12种基础知识总结:

正则表达式替换,遍历目录方法,列表按列排序、去重,字典排序,字典、列表、字符串互转,时间对象操作,命令行参数解析(getopt),print 格式化输出,进制转换,Python调用系统命令或者脚本,Python 读写文件。

1、正则表达式替换目标: 将字符串line中的 overview.gif 替换成其他字符串>>> line = '\'#\'"

>>> mo=re.compile(r'(?<=SRC=)"([\w+\.]+)"',re.I)

>>> mo.sub(r'"\1****"',line)

'\'#\'"

>>> mo.sub(r'replace_str_\1',line)

''< /span>

>>> mo.sub(r'"testetstset"',line)

'\'#\'"

注意: 其中 \1 是匹配到的数据,可以通过这样的方式直接引用

2、遍历目录方法在某些时候,我们需要遍历某个目录找出特定的文件列表,可以通过os.walk方法来遍历,非常方便import os

fileList = []

rootdir = "/data"

for root, subFolders, files in os.walk(rootdir):

if '.svn' in subFolders: subFolders.remove('.svn') # 排除特定目录

for file in files:

if file.find(".t2t") != -1:# 查找特定扩展名的文件

file_dir_path = os.path.join(root,file)

fileList.append(file_dir_path)

print fileList

3、列表按列排序(list sort)

如果列表的每个元素都是一个元组(tuple),我们要根据元组的某列来排序的化,可参考如下方法

下面例子我们是根据元组的第2列和第3列数据来排序的,而且是倒序(reverse=True)>>> a = [('2011-03-17', '2.26', 6429600, '0.0'), ('2011-03-16', '2.26', 12036900, '-3.0'),

('2011-03-15', '2.33', 15615500,'-19.1')]

>>> print a[0][0]

2011-03-17

>>> b = sorted(a, key=lambda result: result[1],reverse=True)

>>> print b

[('2011-03-15', '2.33', 15615500, '-19.1'), ('2011-03-17', '2.26', 6429600, '0.0'),

('2011-03-16', '2.26', 12036900, '-3.0')]

>>> c = sorted(a, key=lambda result: result[2],reverse=True)

>>> print c

[('2011-03-15', '2.33', 15615500, '-19.1'), ('2011-03-16', '2.26', 12036900, '-3.0'),

('2011-03-17', '2.26', 6429600, '0.0')]

4、列表去重(list uniq)有时候需要将list中重复的元素删除,就要使用如下方法

>>> lst= [(1,'sss'),(2,'fsdf'),(1,'sss'),(3,'fd')]

>>> set(lst)

set([(2, 'fsdf'), (3, 'fd'), (1, 'sss')])

>>>

>>> lst = [1, 1, 3, 4, 4, 5, 6, 7, 6]

>>> set(lst)

set([1, 3, 4, 5, 6, 7])

5、字典排序(dict sort)

一般来说,我们都是根据字典的key来进行排序,但是我们如果想根据字典的value值来排序,就使用如下方法>>> from operator import itemgetter

>>> aa = {"a":"1","sss":"2","ffdf":'5',"ffff2":'3'}

>>> sort_aa = sorted(aa.items(),key=itemgetter(1))

>>> sort_aa

[('a', '1'), ('sss', '2'), ('ffff2', '3'), ('ffdf', '5')]

从上面的运行结果看到,按照字典的value值进行排序的

6、字典,列表,字符串互转以下是生成数据库连接字符串,从字典转换到字符串

>>> params= {"server":"mpilgrim","database":"master","uid":"sa","pwd":"secret"}

>>> ["%s=%s" % (k, v)for k, vin params.items()]

['server=mpilgrim','uid=sa','database=master','pwd=secret']

>>>";".join(["%s=%s" % (k, v)for k, vin params.items()])

'server=mpilgrim;uid=sa;database=master;pwd=secret'

下面的例子 是将字符串转化为字典>>> a = 'server=mpilgrim;uid=sa;database=master;pwd=secret'

>>> aa = {}

>>> for i in a.split(';'):aa[i.split('=',1)[0]] = i.split('=',1)[1]

...

>>> aa

{'pwd': 'secret', 'database': 'master', 'uid': 'sa', 'server': 'mpilgrim'}

7、时间对象操作

将时间对象转换成字符串>>> import datetime

>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

'2016-01-16 21:37'

>>>

时间大小比较>>> import time

>>>

>>> t1 = time.strptime('2016-01-20 14:05',"%Y-%m-%d %H:%M")

>>> t2 = time.strptime('2016-01-2 14:05',"%Y-%m-%d %H:%M")

>>> t1 >t2

True

8、命令行参数解析(getopt)

通常在编写一些日运维脚本时,需要根据不同的条件,输入不同的命令行选项来实现不同的功能 在Python中提供了getopt模块很好的实现了命令行参数的解析,下面距离说明。请看如下程序:cat getopt_test2.py

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import os

import os.path

import sys

import getopt

def usage():

print '''

py price.py [option][value]...

-h or --help

-w or --wordattr-file="wordattr文件"

-s or --sflog-pricefile="sflog的价格变化文件"

-t or --tmpdir="临时文件的保存目录,默认为./"

-o or --outputfile="完整信息的保存文件,如果不指定,则输出到stdout"

-a or --wordattr-Complement="较新的wordattr去补全信息,缺省为Null,则丢失新广告的信息"

'''

return 0

if len(sys.argv) == 1:

print '-h or --help for detail'

sys.exit(1)

shortargs = 'hw:s:t:o:a:'

longargs = ['help', 'wordattr=', 'sflog-pricefile=', 'tmpdir=', 'outputfile=', 'wordattr-Complement=']

opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )

if args:

print '-h or --help for detail'

sys.exit(1)

paramdict = {'tmpdir':os.path.abspath(os.curdir), 'outputfile':sys.stdout, 'newwordattr':None }

for opt,val in opts:

if opt in ( '-h', '--help' ):

usage()

continue

if opt in ( '-w', '--wordattr' ):

paramdict['wordattr'] = val

continue

if opt in ( '-s', '--sflog-pricefile' ):

paramdict['pricefile'] = val

continue

if opt in ( '-t', '--tmpdir' ):

paramdict['tmpdir'] = val

continue

if opt in ( '-o', '--outputfile' ):

try:

paramdict['outputfile'] = open(val,'w')

except Exception,e:

#ul_log.write(ul_log.fatal,'%s,%s,@line=%d,@file=%s' \

#%(type(e),str(e),sys._getframe().f_lineno,sys._getframe().f_code.co_filename))

sys.exit(1)

continue

if opt in ( '-a', '--wordattr-Complement' ):

paramdict['newwordattr'] = val

continuepython getopt_test2.py -h

py price.py [option][value]...

-h or --help

-w or --wordattr-file="wordattr文件"

-s or --sflog-pricefile="sflog的价格变化文件"

-t or --tmpdir="临时文件的保存目录,默认为./"

-o or --outputfile="完整信息的保存文件,如果不指定,则输出到stdout"

-a or --wordattr-Complement="较新的wordattr去补全信息,缺省为Null,则丢失新广告的信息"

2. 使用optparser模块处理Unix模式的命令行选项:

optparser模块非常的强大,完全体现了python的“如此简单,如此强大”的特性。

import optparse

def getConfig(ini):

import ConfigParser

try:

cfg = ConfigParser.ConfigParser()

cfg.readfp(open(ini))

print cfg.sections()

except:

pass

if __name__=='__main__':

parser = optparse.OptionParser()

parser.add_option(

"-i",

"--ini",

dest="ini",

default="config.ini",

help="read config from INI file",

metavar="INI"

)

parser.add_option(

"-f",

"--file",

dest="filename",

help="write report to FILE",

metavar="FILE"

)

parser.add_option(

"-q",

"--quiet",

dest="verbose",

action="store_false",

default=True,

help="don't print status messages to stdout"

)

(options, args) = parser.parse_args()

getConfig(options.ini)

print args

9、print 格式化输出

9.1、格式化输出字符串截取字符串输出,下面例子将只输出字符串的前3个字母

>>> str="abcdefg"

>>> print "%.3s" % str

abc

按固定宽度输出,不足使用空格补全,下面例子输出宽度为10

>>> str="abcdefg"

>>> print "%10s" % str

abcdefg

截取字符串,按照固定宽度输出

>>> str="abcdefg"

>>> print "%10.3s" % str

abc

浮点类型数据位数保留

>>> import fpformat

>>> a= 0.0030000000005

>>> b=fpformat.fix(a,6)

>>> print b

0.003000

对浮点数四舍五入,主要使用到round函数

>>> from decimal import *

>>> a ="2.26"

>>> b ="2.29"

>>> c = Decimal(a) - Decimal(b)

>>> print c

-0.03

>>> c / Decimal(a) * 100

Decimal('-1.327433628318584070796460177')

>>> Decimal(str(round(c / Decimal(a) * 100, 2)))

Decimal('-1.33')9.2、进制转换

有些时候需要作不同进制转换,可以参考下面的例子(%x 十六进制,%d 十进制,%o 八进制)

>>> num = 10

>>> print "Hex = %x,Dec = %d,Oct = %o" %(num,num,num)

Hex = a,Dec = 10,Oct = 12

10、Python调用系统命令或者脚本使用 os.system() 调用系统命令 , 程序中无法获得到输出和返回值

>>> import os

>>> os.system('ls -l /proc/cpuinfo')

>>> os.system("ls -l /proc/cpuinfo")

-r--r--r-- 1 root root 0 3月 29 16:53 /proc/cpuinfo

0

使用 os.popen() 调用系统命令, 程序中可以获得命令输出,但是不能得到执行的返回值

>>> out = os.popen("ls -l /proc/cpuinfo")

>>> print out.read()

-r--r--r-- 1 root root 0 3月 29 16:59 /proc/cpuinfo

使用 commands.getstatusoutput() 调用系统命令, 程序中可以获得命令输出和执行的返回值

>>> import commands

>>> commands.getstatusoutput('ls /bin/ls')

(0, '/bin/ls')

11、Python 捕获用户 Ctrl+C ,Ctrl+D 事件

有些时候,需要在程序中捕获用户键盘事件,比如ctrl+c退出,这样可以更好的安全退出程序try:

do_some_func()

except KeyboardInterrupt:

print "User Press Ctrl+C,Exit"

except EOFError:

print "User Press Ctrl+D,Exit"

12、Python 读写文件一次性读入文件到列表,速度较快,适用文件比较小的情况下

track_file = "track_stock.conf"

fd = open(track_file)

content_list = fd.readlines()

fd.close()

for line in content_list:

print line

逐行读入,速度较慢,适用没有足够内存读取整个文件(文件太大)

fd = open(file_path)

fd.seek(0)

title = fd.readline()

keyword = fd.readline()

uuid = fd.readline()

fd.close()

写文件 write 与 writelines 的区别

Fd.write(str) : 把str写到文件中,write()并不会在str后加上一个换行符

Fd.writelines(content) : 把content的内容全部写到文件中,原样写入,不会在每行后面加上任何东西

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值