Python 基础操作知识整理总结


1. 数据对象持久化 
在某些时候,需要将数据对象的内容保存下来,方便下次程序启动时读取,这个就需要将对象持久化,请看如下例子 
 
  import pickle 
   
  # create the test dictionary 
  before_d = {} 
  before_d[1]="Name 1"
  before_d[2]="Name 2"
  before_d[3]="Name 3"
   
  # pickle dump the dictionary 
  fout = open("dict1.dat", "w") 
  pickle.dump(before_d, fout, protocol=0) 
  fout.close() 
   
  # pickle load the dictionary 
  fin = open("dict1.dat", "r") 
  after_d = pickle.load(fin) 
  fin.close() 
   
  print( before_d )  # {1: 'Name 1', 2: 'Name 2', 3: 'Name 3'} 
  print( after_d )  # {1: 'Name 1', 2: 'Name 2', 3: 'Name 3'} 
可以看出,我们将数据对象内容以文件的方式保存,可以作一些简单的cache处理,尤其是在写一些比较小的程序时,非常有用 
 
2. 正则表达式替换 
目标: 将字符串line中的 overview.gif 替换成其他字符串 
 
  >>> line = '<IMG ALIGN="middle" SRC="overview.gif" BORDER="0" ALT="">'
  >>> mo=re.compile(r'(?<=SRC=)"([\w+\.]+)"',re.I) 
   
  >>> mo.sub(r'"\1****"',line) 
  '<IMG ALIGN="middle" SRC="cdn_overview.gif****" BORDER="0" ALT="">'
   
  >>> 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="testetstset" BORDER="0" ALT="">'
注意: 其中 \1 是匹配到的数据,可以通过这样的方式直接引用 
 
3. 遍历目录方法 
在某些时候,我们需要遍历某个目录找出特定的文件列表,可以通过os.walk方法来遍历,非常方便 
 
  import os 
  fileList = [] 
  rootdir = "/tmp"
  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 
 
4. 列表按列排序(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')] 
  • 1
  • 2
  • 3
  • 下一页

相关内容