zoukankan      html  css  js  c++  java
  • 正则表达式在python中的应用

    一、常用符号

      . :匹配任意字符,换行符 除外

       * :匹配前一个字符0次或无限次

        ? :匹配前一个字符0次货1次

      .* :贪心算法

      .*? :非贪心算法

      () :括号内的数据作为结果返回

    二、常用方法

      findall:匹配所有符合规律的内容,返回包含结果的列表

      Search:匹配并提取第一个符合规律的内容,返回一个正则表达式对象(object)

      Sub :替换符合规律的内容,返回替换后的值

    三、代码示例

     1 # coding=utf-8
     2 import re
     3 secret_code = "hadkfalifexxIxxfasdjifja134xxlovexx23345sdfxxyouxx8dfse"
     4 
     5 # .的使用
     6 a = "xy123"
     7 b = re.findall("x..",a)
     8 c = re.findall("x...",a)
     9 print b
    10 print c
    11 # .就是一个占位符,几个.就表示几个字符
    12 
    13 
    14 # *的使用
    15 a = "xyxy123"
    16 b = re.findall("x*",a)
    17 print b
    18 
    19 # ?的使用
    20 a = "xy1x2x3"
    21 b = re.findall("x?",a)
    22 print b
    23 
    24 # .*的使用举例
    25 b = re.findall("xx.*xx",secret_code)
    26 print b
    27 c = re.findall("xx.*?xx",secret_code)
    28 print c
    29 
    30 # ()的使用
    31 b = re.findall("xx(.*?)xx",secret_code)
    32 print b
    33 for str in b:
    34     print str
    35 
    36 
    37 # re.S 使.能包含
    
    38 s = '''sdfxxhello
    39 xxfsdfxxworldxxasdf'''
    40 d = re.findall("xx(.*?)xx",s,re.S)
    41 print d
    42 
    43 # 对比findall与search的区别
    44 s2 = "asdfxxIxx123xxlovexxdfd"
    45 f = re.search("xx(.*?)xx123xx(.*?)xx",s2).group(1)
    46 print f
    47 f2 = re.findall("xx(.*?)xx123xx(.*?)xx",s2)
    48 print f2[0][0]
    49 
    50 # sub的使用
    51 s2 = "123abcssfasdfas123"
    52 output = re.sub("123(.*?)123","123789123",s2)
    53 print output
    54 
    55 # 匹配纯数字
    56 s2 = "asdfasf1234567fasdfas"
    57 b = re.findall("(d+)",s2)
    58 print b

    四、制作简单文本爬虫--爬取百度图片首页分类图片并下载

      实现原理:

        1、保存网页代码

        2、Python读文件加载代码

        3、正则表达式提取图片网址

        4、下载图片

      代码如下所示:

      

     1 # coding=utf-8
     2 import re
     3 import requests
     4 #读取源代码文件
     5 f = open("baidu.txt","r")
     6 html = f.read();
     7 f.close()
     8 
     9 #匹配图片网址
    10 
    11 #先爬大再爬小
    12 url = re.findall('<div class="wrapper_detail_box">(.*?)<div class="wrapper_footer_box">',html,re.S)[0]
    13 pic_url = re.findall('img src="(.*?)"  class="img_pic_layer"',url)
    14 i = 0
    15 for each in pic_url:
    16     print 'now downloading:' + each
    17     #获取图片
    18     pic = requests.get(each)
    19 
    20     #保存图片
    21     fp = open("pic\"+str(i)+".jpg","wb")
    22     fp.write(pic.content)
    23     fp.close()
    24     i += 1
  • 相关阅读:
    UVA12125 March of the Penguins (最大流+拆点)
    UVA 1317 Concert Hall Scheduling(最小费用最大流)
    UVA10249 The Grand Dinner(最大流)
    UVA1349 Optimal Bus Route Design(KM最佳完美匹配)
    UVA1212 Duopoly(最大流最小割)
    UVA1395 Slim Span(kruskal)
    UVA1045 The Great Wall Game(二分图最佳匹配)
    UVA12168 Cat vs. Dog( 二分图最大独立集)
    hdu3488Tour(KM最佳完美匹配)
    UVA1345 Jamie's Contact Groups(最大流+二分)
  • 原文地址:https://www.cnblogs.com/weyoung1987/p/6017606.html
Copyright © 2011-2022 走看看