免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2973 | 回复: 5
打印 上一主题 下一主题

正则表达式的一点应用 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-12-18 12:49 |只看该作者 |倒序浏览
  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的表吧:

论坛徽章:
0
2 [报告]
发表于 2010-12-18 13:14 |只看该作者
很荣幸在这里看到我写的表格

论坛徽章:
0
3 [报告]
发表于 2010-12-18 19:11 |只看该作者
很荣幸在这里看到我写的表格
ixuh 发表于 2010-12-18 13:14



    哇,你把名倒过了...多多指教哈~

论坛徽章:
0
4 [报告]
发表于 2010-12-19 01:07 |只看该作者
回复 3# whitefirer


    不敢当不敢当,一起学习

论坛徽章:
0
5 [报告]
发表于 2010-12-19 20:44 |只看该作者
本帖最后由 whitefirer 于 2010-12-19 20:48 编辑

补充一点,这个是对本地网页文件分析的,当然其实应当判断一下它的编码方式的,得用第三方库chardet:  http://chardet.feedparser.org/download/
, 如下:
  1.                 chartype = chardet.detect(title[0]).values()[1]
  2.                 title[0] = title[0].decode(chartype).encode('GB18030')#gb2312 双字节,区别再于GB18030是最新标准字比gb2312多,不过gb2312跟uft8可兼容的系统(包括手机)更多
复制代码
当然,如果是在线分析的网页的话,可以用正则提取head 里的charset,而用chardet也是可以的

论坛徽章:
0
6 [报告]
发表于 2010-12-20 12:48 |只看该作者
本帖最后由 whitefirer 于 2010-12-20 16:32 编辑

修改:
  1. # -*- coding: utf-8 -*-
  2. '''
  3.         要注意的是:
  4.         1. 现在的记录方式是追加方式,如果要用覆盖方式,请自行用logo记录,然后一次写入(似乎它只能一次)
  5.         2. 复制网页文件到指定路径下的功能已注释,如有需要,请自行修改
  6.         3. 现写了的网页格式有'html', 'mht', 'jsp', 'htm', 'php', 'shtml', 'asp',如有需要,请自行添加
  7.         4. ....
  8. '''
  9. import os, sys, re, shutil, binascii, chardet
  10. startpath = "G:\\Python25\\"                                        #被操作的文件夹
  11. targetpath = "G:\\test\\"                                                #复制文件的目的路径
  12. logopath = "G:\\test\\logo.txt"                                        #提取title存入的文件
  13. notitle = '无标题'
  14. codetype = 'utf8'#GB18030如果不行改成uft8
  15. #gb2312 双字节,区别再于GB18030是最新标准字比gb2312多,不过gb2312跟uft8可兼容的系统(包括手机)更多
  16. g_wap_pattern = ['html', 'mht', 'jsp', 'htm', 'php', 'shtml', 'asp', 'xhtml', 'aspx']
  17.                                                                                                 #各种网页格式
  18. #logo = ["logo:\r\n"]
  19. #以上写在这里只是为了便于修改,如果有需要,也可以写成管道方式或其它方式

  20. '''
  21. def ansymhttitle(string):                                                #不能得到非汉字,并且做复杂了
  22.         strinfo = re.compile(r'=..')
  23.         strlist = strinfo.findall(string)
  24.         string = ''
  25.        
  26.         for i in range(0, len(strlist)):
  27.                 strlist[i] = hex(int(strlist[i].replace('=', '') , 16)).replace('0x', '') # 多此一举
  28.                 string = string + binascii.a2b_hex(strlist[i])
  29.         return string
  30. '''

  31. def makefolder(inFolderName, FolderName):
  32.     if os.path.isdir( inFolderName ):
  33.         newFolderName = inFolderName + '' + FolderName
  34.         if os.path.isdir( newFolderName ):
  35.             print(newFolderName," Exists already ")
  36.         else:
  37.             os.mkdir(newFolderName)
  38.             print(newFolderName," Create OK ")
  39.     else:
  40.         print(inFolderName," not exists, script stop ")
  41.                
  42. def ansymhttitle(string):
  43.         string = string.replace('=\n', '')                        #去除'=\n' 也可以换成\n
  44.         strinfo = re.compile(r'=\w\w|=\s')#r'=..'        # 匹配字母与数字
  45.         strlist = strinfo.findall(string)
  46.         #print strlist                                                                #测试时用

  47.         for i in range(0, len(strlist)):
  48.                 string = string.replace(strlist[i], binascii.a2b_hex(strlist[i].replace('=', '')))
  49.         return string                                                                #替换为相应ascii码后返回
  50.        
  51. def gettitle(url, waptype):
  52.         file_object = open(url)                                                #开打文件
  53.         try:
  54.                 content = file_object.read( )                        #读取文件内容
  55.                 #chartype = chardet.detect(content).values()[1]
  56.                 title = re.findall(r"<title>([\s\S]*?)</title>", content, re.M)
  57.                 #意思是取<title></title>间的任意多的所有字符\s是空白字符\S是非空白字符
  58.                 #r"<title>\s*(.*?)\s*</title>", 这个不对换行进行判断,现在的可以
  59.                 #titlepattern = re.compile(r"<TITLE>[...]</TITLE>")
  60.                 #title = titlepattern.search(content);

  61.                 if(title):
  62.                         if '' == title[0]:
  63.                                 title[0] = notitle                                #找到为空时,无标题
  64.                 else:
  65.                         title = re.findall(r"<TITLE>([\s\S]*?)</TITLE>", content, re.M)
  66.                         if title:                                                        #上面对大写的<TITLE>标签进行判断
  67.                                 if '' == title[0]:
  68.                                         title[0] = notitle                        #找到为空时,无标题
  69.                         else:
  70.                                 title.append(notitle)                        #未找到时,无标题
  71.                                
  72.                 if not cmp(waptype, "mht"):                                #如果是mht文件,则对其title解码
  73.                         title[0] = ansymhttitle(title[0])
  74.                        
  75.                 chartype = chardet.detect(title[0]).values()[1]
  76.                 print chartype
  77.                 title[0] = title[0].replace('\n', '')        #去掉换行符(主要针对<title>后面的)
  78.                 title[0] = title[0].decode(chartype).encode(codetype)
  79.                 print title[0].decode(codetype).encode('GB18030')
  80.                                                                                                 #这里只是为了屏幕上显示的不是乱码,如果想提高效率,可以删除
  81.         finally:
  82.                 file_object.close( )                                        #关闭文件
  83.                
  84.         return title[0]
  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(basenames):
  95.                                 #print basenames
  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.                                         #拷贝文件到目标地
  103.                                         title = gettitle(path, g_wap_pattern[i])        #得到该网页的title
  104.                                         folder = dirname.split("\\")[-1]
  105.                                         logostr = "http://" + folder + "/" + "\t" + title + "\n"
  106.                                         makefolder(targetpath, folder)
  107.                                         shutil.copyfile(path, targetpath +folder + '\\' + basename)
  108.                                         file_logo = file(logopath, 'a')                                #以追加方式打开
  109.                                         try:
  110.                                                 file_logo.write(logostr)                                #写入信息
  111.                                         except IOError:  
  112.                                                 print('IOError')
  113.                                         #finally:
  114.                                         #file_logo.colse()
  115.                                         break
  116.                                
  117. if __name__ == "__main__" :
  118.         try :
  119.                 searchfile(1, startpath)                                #递归搜索指定路径下的文件
  120.                 '''
  121.                 print logo
  122.                 print len(logo)
  123.                 file_logo = open("G:\\test\\logo.txt", 'w')
  124.                 try:
  125.                         for i int range( 0, len(logo)):
  126.                                 file_logo.write(logo[i])
  127.                 except IOError:  
  128.                         print('IOError')
  129.                 finally:       
  130.                         file_logo.colse()
  131.                 '''
  132.         except:
  133.                 print "execute search file fun error"
  134.         raw_input('Enter to continue...')                        #暂停
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP