Python语言的12个基础知识点小结

开发 后端
这篇文章主要介绍了Python语言的12个基础知识点小结,包含正则表达式替换、遍历目录方法、列表按列排序、去重、字典排序等,需要的朋友可以参考下!

[[393938]]

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

1、正则表达式替换

目标: 将字符串line中的 overview.gif 替换成其他字符串。

  1. >>> line = '<IMG ALIGN="middle" SRC=\'#\'" />' 
  2. >>> mo=re.compile(r'(?<=SRC=)"([\w+\.]+)"',re.I)  
  3. >>> mo.sub(r'"\1****"',line) 
  4. '<IMG ALIGN="middle" SRC=\'#\'" /span> 
  5. >>> mo.sub(r'replace_str_\1',line) 
  6. '<IMG ALIGN="middle" replace_str_overview.gif BORDER="0" ALT="">'< /span> 
  7. >>> mo.sub(r'"testetstset"',line) 
  8. '<IMG ALIGN="middle" SRC=\'#\'" /span> 

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

2、遍历目录方法

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

  1. import os 
  2. fileList = [] 
  3. rootdir = "/data" 
  4. for root, subFolders, files in os.walk(rootdir): 
  5. if '.svn' in subFolders: subFolders.remove('.svn')  # 排除特定目录 
  6. for file in files: 
  7.   if file.find(".t2t") != -1:# 查找特定扩展名的文件 
  8.       file_dir_path = os.path.join(root,file) 
  9.       fileList.append(file_dir_path)  
  10. print fileList 

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

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

下面例子我们是根据元组的第2列和第3列数据来排序的,而且是倒序(reverse=True)。

  1. >>> a = [('2011-03-17''2.26', 6429600, '0.0'), ('2011-03-16''2.26', 12036900, '-3.0'), 
  2.  ('2011-03-15''2.33', 15615500,'-19.1')] 
  3. >>> print a[0][0] 
  4. 2011-03-17 
  5. >>> b = sorted(a, key=lambda result: result[1],reverse=True
  6. >>> print b 
  7. [('2011-03-15''2.33', 15615500, '-19.1'), ('2011-03-17''2.26', 6429600, '0.0'), 
  8. ('2011-03-16''2.26', 12036900, '-3.0')] 
  9. >>> c = sorted(a, key=lambda result: result[2],reverse=True
  10. >>> print c 
  11. [('2011-03-15''2.33', 15615500, '-19.1'), ('2011-03-16''2.26', 12036900, '-3.0'), 
  12. ('2011-03-17''2.26', 6429600, '0.0')] 

 4、列表去重(list uniq)

有时候需要将list中重复的元素删除,就要使用如下方法:

  1. >>> lst= [(1,'sss'),(2,'fsdf'),(1,'sss'),(3,'fd')] 
  2. >>> set(lst) 
  3. set([(2, 'fsdf'), (3, 'fd'), (1, 'sss')]) 
  4. >>> 
  5. >>> lst = [1, 1, 3, 4, 4, 5, 6, 7, 6] 
  6. >>> set(lst) 
  7. set([1, 3, 4, 5, 6, 7]) 

 5、字典排序(dict sort)

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

  1. >>> from operator import itemgetter 
  2. >>> aa = {"a":"1","sss":"2","ffdf":'5',"ffff2":'3'
  3. >>> sort_aa = sorted(aa.items(),key=itemgetter(1)) 
  4. >>> sort_aa 
  5. [('a''1'), ('sss''2'), ('ffff2''3'), ('ffdf''5')] 

 6、字典,列表,字符串互转

以下是生成数据库连接字符串,从字典转换到字符串。

  1. >>> params = {"server":"mpilgrim""database":"master""uid":"sa""pwd":"secret"
  2. >>> ["%s=%s" % (k, v) for k, v in params.items()] 
  3. ['server=mpilgrim''uid=sa''database=master''pwd=secret'
  4. >>> ";".join(["%s=%s" % (k, v) for k, v in params.items()]) 
  5. 'server=mpilgrim;uid=sa;database=master;pwd=secret' 

 下面的例子,是将字符串转化为字典。

  1. >>> a = 'server=mpilgrim;uid=sa;database=master;pwd=secret' 
  2. >>> aa = {} 
  3. >>> for i in a.split(';'):aa[i.split('=',1)[0]] = i.split('=',1)[1] 
  4. ... 
  5. >>> aa 
  6. {'pwd''secret''database''master''uid''sa''server''mpilgrim'

 7、时间对象操作

将时间对象转换成字符串。

  1. >>> import datetime 
  2. >>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M"
  3.   '2011-01-20 14:05'  

 时间大小比较。

  1. >>> import time 
  2. >>> t1 = time.strptime('2011-01-20 14:05',"%Y-%m-%d %H:%M"
  3. >>> t2 = time.strptime('2011-01-20 16:05',"%Y-%m-%d %H:%M"
  4. >>> t1 > t2 
  5.   False 
  6. >>> t1 < t2 
  7.   True  

 时间差值计算,计算8小时前的时间。

  1. >>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M"
  2.   '2011-01-20 15:02' 
  3. >>> (datetime.datetime.now() - datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M"
  4.   '2011-01-20 07:03'  

 将字符串转换成时间对象。

  1. >>> endtime=datetime.datetime.strptime('20100701',"%Y%m%d"
  2. >>> type(endtime) 
  3.   <type 'datetime.datetime'
  4. >>> print endtime 
  5.   2010-07-01 00:00:00  

 将从 1970-01-01 00:00:00 UTC 到现在的秒数,格式化输出。

  1. >>> import time 
  2. >>> a = 1302153828 
  3. >>> time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(a)) 
  4.   '2011-04-07 13:23:48' 

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

通常在编写一些日运维脚本时,需要根据不同的条件,输入不同的命令行选项来实现不同的功能。

在Python中提供了getopt模块很好的实现了命令行参数的解析,下面距离说明。请看如下程序:

  1. #!/usr/bin/env python 
  2. # -*- coding: utf-8 -*- 
  3. import sys,os,getopt 
  4. def usage(): 
  5. print ''''
  6. Usage: analyse_stock.py [options...] 
  7. Options: 
  8. -e : Exchange Name 
  9. -c : User-Defined Category Name 
  10. -f : Read stock info from file and save to db 
  11. -d : delete from db by stock code 
  12. -n : stock name 
  13. -s : stock code 
  14. -h : this help info 
  15. test.py -s haha -n "HA Ha" 
  16. ''
  17. try: 
  18. opts, args = getopt.getopt(sys.argv[1:],'he:c:f:d:n:s:'
  19. except getopt.GetoptError: 
  20. usage() 
  21. sys.exit() 
  22. if len(opts) == 0: 
  23. usage() 
  24. sys.exit()  
  25. for opt, arg in opts: 
  26. if opt in ('-h''--help'): 
  27.   usage() 
  28.   sys.exit() 
  29. elif opt == '-d'
  30.   print "del stock %s" % arg 
  31. elif opt == '-f'
  32.   print "read file %s" % arg 
  33. elif opt == '-c'
  34.   print "user-defined %s " % arg 
  35. elif opt == '-e'
  36.   print "Exchange Name %s" % arg 
  37. elif opt == '-s'
  38.   print "Stock code %s" % arg 
  39. elif opt == '-n'
  40.   print "Stock name %s" % arg  
  41. sys.exit() 

 9、print 格式化输出

9.1、格式化输出字符串

截取字符串输出,下面例子将只输出字符串的前3个字母。

  1. >>> str="abcdefg" 
  2. >>> print "%.3s" % str 
  3.   abc 

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

  1. >>> str="abcdefg" 
  2. >>> print "%10s" % str 
  3.      abcdefg 

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

  1. >>> str="abcdefg" 
  2. >>> print "%10.3s" % str 
  3.          abc 

 浮点类型数据位数保留。

  1. >>> import fpformat 
  2. >>> a= 0.0030000000005 
  3. >>> b=fpformat.fix(a,6) 
  4. >>> print b 
  5.   0.003000 

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

  1. >>> from decimal import * 
  2. >>> a ="2.26" 
  3. >>> b ="2.29" 
  4. >>> c = Decimal(a) - Decimal(b) 
  5. >>> print c 
  6.   -0.03 
  7. >>> c / Decimal(a) * 100 
  8.   Decimal('-1.327433628318584070796460177'
  9. >>> Decimal(str(round(c / Decimal(a) * 100, 2))) 
  10.   Decimal('-1.33'

 9.2、进制转换

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

  1. >>> num = 10 
  2. >>> print "Hex = %x,Dec = %d,Oct = %o" %(num,num,num) 
  3.   Hex = a,Dec = 10,Oct = 12 

 10、Python调用系统命令或者脚本

使用 os.system() 调用系统命令 , 程序中无法获得到输出和返回值。

  1. >>> import os 
  2. >>> os.system('ls -l /proc/cpuinfo'
  3. >>> os.system("ls -l /proc/cpuinfo"
  4.   -r--r--r-- 1 root root 0  3月 29 16:53 /proc/cpuinfo 
  5.   0  

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

  1. >>> out = os.popen("ls -l /proc/cpuinfo"
  2. >>> print out.read() 
  3.   -r--r--r-- 1 root root 0  3月 29 16:59 /proc/cpuinfo   

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

  1. >>> import commands 
  2. >>> commands.getstatusoutput('ls /bin/ls'
  3.   (0, '/bin/ls'

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

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

  1. try: 
  2.     do_some_func() 
  3. except KeyboardInterrupt: 
  4.     print "User Press Ctrl+C,Exit" 
  5. except EOFError: 
  6.     print "User Press Ctrl+D,Exit" 

 12、Python 读写文件

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

  1. track_file = "track_stock.conf" 
  2. fd = open(track_file) 
  3. content_list = fd.readlines() 
  4. fd.close() 
  5. for line in content_list: 
  6.     print line 

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

  1. fd = open(file_path) 
  2. fd.seek(0) 
  3. title = fd.readline() 
  4. keyword = fd.readline() 
  5. uuid = fd.readline() 
  6. fd.close()   

 写文件 write 与 writelines 的区别 。

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

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

这篇文章主要介绍了Python语言的12个基础知识点小结,包含正则表达式替换、遍历目录方法、列表按列排序、去重、字典排序等,需要的朋友可以参考下!

 

责任编辑:姜华 来源: 今日头条
相关推荐

2013-11-25 11:41:54

手游出海海外推广渠道

2022-03-10 16:51:46

C语言代码if语句

2015-11-16 09:51:06

IPV6网路协议

2024-01-07 19:54:51

2021-01-23 12:47:19

MySQL数据库Go语言

2023-12-22 15:32:20

2010-01-19 14:45:35

C++语言

2020-09-25 16:52:57

Python

2019-07-15 12:40:02

Linux基础知识程序员

2023-07-14 15:10:17

PythonAsyncIO库

2011-07-22 09:43:37

java

2011-07-21 17:45:02

java

2011-07-21 17:18:52

java

2011-07-22 10:38:04

java

2011-07-22 10:02:07

java

2011-07-21 17:33:27

JAVA

2009-08-02 21:47:35

安防线缆

2022-08-01 07:42:17

线程安全场景

2020-02-07 09:59:29

Python异常处理语言

2020-10-07 15:15:41

Python
点赞
收藏

51CTO技术栈公众号