Python编程中常用的12种基础知识总结
原地址:http://blog.jobbole.com/48541/
Python编程中常用的12种基础知识总结:正则表达式替换,遍历目录方法,列表按列排序、去重,字典排序,字典、列表、字符串互转,时间对象操作,命令行参数解析(getopt),print 格式化输出,进制转换,Python调用系统命令或者脚本,Python 读写文件。
1、正则表达式替换
目标: 将字符串line中的 overview.gif 替换成其他字符串
|
1
2
3
4
5
6
7
8
9
10
11
|
>>> line = '<IMG ALIGN="middle" SRC=\'#\'" /span> >>> mo=re.compile(r'(?<=SRC=)"([\w+\.]+)"',re.I) >>> mo.sub(r'"\1****"',line) '<IMG ALIGN="middle" SRC=\'#\'" /span> >>> mo.sub(r'replace_str_\1',line) '<IMG ALIGN="middle" replace_str_overview.gif BORDER="0" ALT="">'< /span> >>> mo.sub(r'"testetstset"',line) '<IMG ALIGN="middle" SRC=\'#\'" /span> |
注意: 其中 \1 是匹配到的数据,可以通过这样的方式直接引用
2、遍历目录方法
在某些时候,我们需要遍历某个目录找出特定的文件列表,可以通过os.walk方法来遍历,非常方便
|
1
2
3
4
5
6
7
8
9
10
11
|
import osfileList = []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)
|
1
2
3
4
5
6
7
8
9
10
11
12
|
>>> 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中重复的元素删除,就要使用如下方法
|
1
2
3
4
5
6
7
|
>>> 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值来排序,就使用如下方法
|
1
2
3
4
5
|
>>> 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、字典,列表,字符串互转
以下是生成数据库连接字符串,从字典转换到字符串
|
1
2
3
4
5
|
>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}>>> ["%s=%s" % (k, v) for k, v in params.items()]['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']>>> ";".join(["%s=%s" % (k, v) for k, v in params.items()])'server=mpilgrim;uid=sa;database=master;pwd=secret' |
下面的例子 是将字符串转化为字典
|
1
2
3
4
5
6
|
>>> 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、时间对象操作
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
将时间对象转换成字符串>>> import datetime>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M") '2011-01-20 14:05'时间大小比较>>> import time>>> t1 = time.strptime('2011-01-20 14:05',"%Y-%m-%d %H:%M")>>> t2 = time.strptime('2011-01-20 16:05',"%Y-%m-%d %H:%M")>>> t1 > t2 False>>> t1 < t2 True时间差值计算,计算8小时前的时间>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M") '2011-01-20 15:02'>>> (datetime.datetime.now() - datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M") '2011-01-20 07:03'将字符串转换成时间对象>>> endtime=datetime.datetime.strptime('20100701',"%Y%m%d")>>> type(endtime) <type 'datetime.datetime'>>>> print endtime 2010-07-01 00:00:00将从 1970-01-01 00:00:00 UTC 到现在的秒数,格式化输出 >>> import time>>> a = 1302153828>>> time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(a)) '2011-04-07 13:23:48' |
8、命令行参数解析(getopt)
通常在编写一些日运维脚本时,需要根据不同的条件,输入不同的命令行选项来实现不同的功能 在Python中提供了getopt模块很好的实现了命令行参数的解析,下面距离说明。请看如下程序:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
#!/usr/bin/env python# -*- coding: utf-8 -*-import sys,os,getoptdef usage():print '''''Usage: analyse_stock.py [options...]Options:-e : Exchange Name-c : User-Defined Category Name-f : Read stock info from file and save to db-d : delete from db by stock code-n : stock name-s : stock code-h : this help infotest.py -s haha -n "HA Ha"'''try:opts, args = getopt.getopt(sys.argv[1:],'he:c:f:d:n:s:')except getopt.GetoptError:usage()sys.exit()if len(opts) == 0:usage()sys.exit() for opt, arg in opts:if opt in ('-h', '--help'): usage() sys.exit()elif opt == '-d': print "del stock %s" % argelif opt == '-f': print "read file %s" % argelif opt == '-c': print "user-defined %s " % argelif opt == '-e': print "Exchange Name %s" % argelif opt == '-s': print "Stock code %s" % argelif opt == '-n': print "Stock name %s" % arg sys.exit() |
9、print 格式化输出
9.1、格式化输出字符串
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
截取字符串输出,下面例子将只输出字符串的前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 八进制)
|
1
2
3
|
>>> num = 10>>> print "Hex = %x,Dec = %d,Oct = %o" %(num,num,num) Hex = a,Dec = 10,Oct = 12 |
10、Python调用系统命令或者脚本
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
使用 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退出,这样可以更好的安全退出程序
|
1
2
3
4
5
6
|
try: do_some_func()except KeyboardInterrupt: print "User Press Ctrl+C,Exit"except EOFError: print "User Press Ctrl+D,Exit" |
12、Python 读写文件
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
一次性读入文件到列表,速度较快,适用文件比较小的情况下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的内容全部写到文件中,原样写入,不会在每行后面加上任何东西 |
Python编程中常用的12种基础知识总结的更多相关文章
- 【转载】Python编程中常用的12种基础知识总结
Python编程中常用的12种基础知识总结:正则表达式替换,遍历目录方法,列表按列排序.去重,字典排序,字典.列表.字符串互转,时间对象操作,命令行参数解析(getopt),print 格式化输出,进 ...
- python编程:从入门到实践----基础知识>第4章练习
4-1 比萨 :想出至少三种你喜欢的比萨,将其名称存储在一个列表中,再使用for 循环将每种比萨的名称都打印出来. a.修改这个for 循环,使其打印包含比萨名称的句子,而不仅仅是比萨的名称.对于每种 ...
- python中常用的九种数据预处理方法分享
Spyder Ctrl + 4/5: 块注释/块反注释 本文总结的是我们大家在python中常见的数据预处理方法,以下通过sklearn的preprocessing模块来介绍; 1. 标准化(St ...
- python中常用的九种预处理方法
本文总结的是我们大家在python中常见的数据预处理方法,以下通过sklearn的preprocessing模块来介绍; 1. 标准化(Standardization or Mean Removal ...
- 【原】实时渲染中常用的几种Rendering Path
[原]实时渲染中常用的几种Rendering Path 本文转载请注明出处 —— polobymulberry-博客园 本文为我的图形学大作业的论文部分,介绍了一些Rendering Path,比较简 ...
- Python编程中 re正则表达式模块 介绍与使用教程
Python编程中 re正则表达式模块 介绍与使用教程 一.前言: 这篇文章是因为昨天写了一篇 shell script 的文章,在文章中俺大量调用多媒体素材与网址引用.这样就会有一个问题就是:随着俺 ...
- 解析Python编程中的包结构
解析Python编程中的包结构 假设你想设计一个模块集(也就是一个"包")来统一处理声音文件和声音数据.通常由它们的扩展有不同的声音格式,例如:WAV,AIFF,AU),所以你可能 ...
- 详解Python编程中基本的数学计算使用
详解Python编程中基本的数学计算使用 在Python中,对数的规定比较简单,基本在小学数学水平即可理解. 那么,做为零基础学习这,也就从计算小学数学题目开始吧.因为从这里开始,数学的基础知识列位肯 ...
- 使用Word API打开Word文档 ASP.NET编程中常用到的27个函数集
使用Word API(非Openxml)打开Word文档简单示例(必须安装Word) 首先需要引入参照Microsoft.Office.Interop.Word 代码示例如下: public void ...
随机推荐
- 前端面试题整理(js)
1.HTTP协议的状态消息都有哪些? HTTP状态码是什么: Web服务器用来告诉客户端,发生了什么事. 状态码分类: 1**:信息提示.请求收到,继续处理2**:成功.操作成功收到,分析.接受3** ...
- Win32 进程间通信的分析与比较(13种方法)
1 进程与进程通信 进程是装入内存并准备执行的程序,每个进程都有私有的虚拟地址空间,由代码.数据以及它可利用的系统资源(如文件.管道等)组成.多进程/多线 程是Windows操作系统的一个基本特征.M ...
- 分享最新15个加速 Web 开发的框架和工具(梦想天空)
我们为开发人员挑选了15个最新的 Web 开发框架,你肯定尝试一下这些新鲜的框架,有的可能略微复杂,有的提供了很多的配置选项,也有一些窗口小部件和界面交互的选择.他们将帮助你创建更优秀的网站,提供给 ...
- 再淡spring jdbc 连接池断开重连设置
先看一段错误日志: ### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConne ...
- Qt显示调用vs中的dll
网上看到很多文章写调用vc的dll,但我尝试了总是出问题,下面结合参考别人的文章,实现了Qt显示调用vs中c接口的dll. 具体直接上代码: vs中的代码: TMax.h: #ifdef TMAX # ...
- vld(Visual Leak Detector) 内存泄露检测工具
初识Visual Leak Detector 灵活自由是C/C++语言的一大特色,而这也为C/C++程序员出了一个难题.当程序越来越复 杂时,内存的管理也会变得越加复杂,稍有不慎就会出现内存问题.内存 ...
- WPF/Silverlight深度解决方案:(一)解锁被Storyboard束缚的关联属性
原文 WPF/Silverlight深度解决方案:(一)解锁被Storyboard束缚的关联属性 如果您在使用WPF/Silverlight进行相关动画开发中使用了Storyboard,并对关联属性进 ...
- javascript 回调函数应用
回调函数是什么在学习之前还真不知道js回调函数怎么使用及作用了,下面本文章把我在学习回调函数例子给各位同学介绍一下吧,有需了解的同学不防进入参考. 回调函数原理: 我现在出发,到了通知你”这是一个异步 ...
- android ListView中CheckBox错位的解决
貌似已经非常晚了,可是还是想记下笔记,想让今天完满. 在ListView中加了checkBox,但是发现点击改变其选中状态的时候,发现其位置错乱.状态改变的并非你选中的,百思不得其解.后面通过上网查资 ...
- TCP/IP协议全解析
TCP/IP 是用于因特网 (Internet) 的通信协议. TCP/IP 是供已连接因特网的计算机进行通信的通信协议. TCP/IP 指传输控制协议/网际协议(Transmission Contr ...