+ -
当前位置:首页 → 问答吧 → 正则表达式的一点应用

正则表达式的一点应用

时间:2010-12-18

来源:互联网

  1. # -*- coding: utf-8 -*-
  2. '''
  3.         Filename: searchfile.py
  4.         Discription: 搜索指定目录下的网页文件,并从文件中提取title
  5.         By: whitefirer
  6.        
  7. '''

  8. '''
  9.         要注意的是:
  10.         1. 现在的记录方式是追加方式,如果要用覆盖方式,请自行用logo记录,然后一次写入(似乎它只能一次)
  11.         2. 复制网页文件到指定路径下的功能已注释,如有需要,请自行修改
  12.         3. 现写了的网页格式有'html', 'mht', 'jsp', 'htm', 'php', 'shtml', 'asp',如有需要,请自行添加
  13.         4. ....
  14. '''
  15. import os, sys, re, shutil, binascii
  16. startpath = "G:\\Python25"                                                #被操作的文件夹
  17. targetpath = "G:\\test\\"                                                #复制文件的目的路径
  18. logopath = "G:\\test\\logo.txt"                                        #提取title存入的文件
  19. g_wap_pattern = ['html', 'mht', 'jsp', 'htm', 'php', 'shtml', 'asp', 'xhtml', 'aspx']
  20.                                                                 #各种网页格式
  21. #logo = ["logo:\r\n"]
  22. #以上写在这里只是为了便于修改,如果有需要,也可以写成管道方式或其它方式
  23. '''
  24. def ansymhttitle(string):                                                #不能得到非汉字,并且做复杂了
  25.         strinfo = re.compile(r'=..')
  26.         strlist = strinfo.findall(string)
  27.         string = ''
  28.        
  29.         for i in range(0, len(strlist)):
  30.                 strlist[i] = hex(int(strlist[i].replace('=', '') , 16)).replace('0x', '') # 多此一举
  31.                 string = string + binascii.a2b_hex(strlist[i])
  32.         return string
  33. '''
  34. def ansymhttitle(string):
  35.         string = string.replace('=\n', '')                                        #去除'=\n' 也可以换成\n
  36.         strinfo = re.compile(r'=\w\w|=\s')#r'=..'                                # 匹配字母与数字
  37.         strlist = strinfo.findall(string)
  38.         #print strlist                                                #测试时用

  39.         for i in range(0, len(strlist)):
  40.                 string = string.replace(strlist[i], binascii.a2b_hex(strlist[i].replace('=', '')))
  41.         return string                                                #替换为相应ascii码后返回
  42.        
  43. def gettitle(url, waptype):
  44.         file_object = open(url)                                        #开打文件
  45.         try:
  46.                 content = file_object.read( )                                #读取文件内容

  47.                 title = re.findall(r"<title>([\s\S]*?)</title>", content, re.M)
  48.                 #意思是取<title></title>间的任意多的所有字符\s是空白字符\S是非空白字符
  49.                 #r"<title>\s*(.*?)\s*</title>", 这个不对换行进行判断,现在的可以
  50.                 #titlepattern = re.compile(r"<TITLE>[...]</TITLE>")
  51.                 #title = titlepattern.search(content);
  52.                
  53.                 if(title):
  54.                         if '' == title[0]:
  55.                                 title[0] = '无标题'                        #找到为空时,无标题
  56.                 else:
  57.                         title = re.findall(r"<TITLE>([\s\S]*?)</TITLE>", content, re.M)
  58.                         if title:                                        #上面对大写的<TITLE>标签进行判断
  59.                                 if '' == title[0]:
  60.                                         title[0] = '无标题'                #找到为空时,无标题
  61.                         else:
  62.                                 title.append('无标题')                #未找到时,无标题
  63.                                
  64.                 if not cmp(waptype, "mht"):                                #如果是mht文件,则对其title解码
  65.                         title[0] = ansymhttitle(title[0])
  66.                
  67.                 title[0] = title[0].replace('\n', '')                        #去掉换行符(主要针对<title>后面的)
  68.                 print title[0]
  69.                
  70.         finally:
  71.                 file_object.close( )                                        #关闭文件
  72.                
  73.         lastpath = re.findall(r"\\([\s\S]*?)\\", url, re.M)
  74.         n = len(lastpath) - 1
  75.         #logo.append("http://" + lastpath[n] + "/" + "\t" + title[0] + "\n")
  76.         logostr = "http://" + lastpath[n] + "/" + "\t" + title[0] + "\n"
  77.        
  78.         file_logo = file(logopath, 'a')                                        #以追加方式打开
  79.         try:
  80.                 file_logo.write(logostr)                                #写入信息
  81.         except IOError:  
  82.                 print('IOError')
  83.         #finally:
  84.                 #file_logo.colse()
  85.                
  86. def searchfile(n, dirname):  
  87.          
  88.         for basename in os.listdir(dirname):   
  89.                 path = os.path.join(dirname, basename)                #得到路径下所有的文件的完整路径

  90.                 if os.path.isdir(path):         
  91.                         searchfile(n + 1, path)                         #递归搜索文件
  92.                 else:
  93.                         #pattern = re.compile(r'(.*?).html') #r'(.*?).txt'
  94.                         #if pattern.match(basename):
  95.                                 #print basename
  96.                         if not os.path.getsize(path):                        #判断文件的大小,如果为空则不执行下面的代码
  97.                                 continue
  98.                                
  99.                         for i in range(0, len(g_wap_pattern)):
  100.                                 if path.lower().endswith(g_wap_pattern[i]):
  101.                                         print '文件路径:' + path        #当是网页文件后缀时打印路径
  102.                                         #shutil.copyfile(path, targetpath + basename)
  103.                                         #拷贝文件到目标地
  104.                                         gettitle(path, g_wap_pattern[i])#得到该网页的title
  105.                                         break
  106.                                
  107. if __name__ == "__main__" :
  108.         try :
  109.                 searchfile(1, startpath)                                 #递归搜索指定路径下的文件
  110.                 '''
  111.                 print logo
  112.                 print len(logo)
  113.                 file_logo = open("G:\\test\\logo.txt", 'w')
  114.                 try:
  115.                         for i int range( 0, len(logo)):
  116.                                 file_logo.write(logo[i])
  117.                 except IOError:  
  118.                         print('IOError')
  119.                 finally:       
  120.                         file_logo.colse()
  121.                 '''
  122.         except:
  123.                 print "execute search file fun error"
  124.         raw_input('Enter to continue...')                        #暂停
  125.        
复制代码
呃,再附一张re的表吧:
下载 (411.3 KB)
re
2010-12-18 12:48

作者: whitefirer   发布时间: 2010-12-18

很荣幸在这里看到我写的表格

作者: ixuh   发布时间: 2010-12-18