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 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)
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')]) >>> >>> 目标: 将字符串line中的 overview.gif 替换成其他字符串
注意: 其中 \1 是匹配到的数据,可以通过这样的方式直接引用 2、遍历目录方法
3、列表按列排序(list sort) 下面例子我们是根据元组的第2列和第3列数据来排序的,而且是倒序(reverse=True)
4、列表去重(list uniq)
|