最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python正則表達(dá)式re模塊講解以及其案例舉例

 更新時(shí)間:2022年09月30日 11:12:58   作者:hhh江月  
Python中re模塊主要功能是通過正則表達(dá)式是用來匹配處理字符串的 ,下面這篇文章主要給大家介紹了關(guān)于Python正則表達(dá)式re模塊講解以及其案例舉例的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下

一、re模塊簡介

Python 的 re 模塊(Regular Expression 正則表達(dá)式)提供各種正則表達(dá)式的匹配操作,和 Perl 腳本的正則表達(dá)式功能類似,使用這一內(nèi)嵌于 Python 的語言工具,盡管不能滿足所有復(fù)雜的匹配情況,但足夠在絕大多數(shù)情況下能夠有效地實(shí)現(xiàn)對復(fù)雜字符串的分析并提取出相關(guān)信息。

二、正則表達(dá)式的基本概念

所謂的正則表達(dá)式,即就是說:

通過設(shè)定匹配的字符串的格式來在一個(gè)文本中找出所有符合該格式的一串字符。

1、正則表達(dá)式的語法介紹:

1)特殊字符:

, ., ^, $, {}, [], (), | 等

以上的特殊字符必須使用\來轉(zhuǎn)義,這樣才能使用原來的意思。

2)字符類

[] 中的一個(gè)或者是多個(gè)字符被稱為字符類,字符類在匹配時(shí)如果沒有指定量詞則只會(huì)匹配其中的一個(gè)。

字符類的范圍可以進(jìn)行指定。

比如:

1> [a-zA-Z0-9]表示從a到z,從A到Z,0到9之間的任意一個(gè)字符;

2> 左方括號后面可以跟隨一個(gè) ^ ,表示否定一個(gè)字符類,字符類在匹配時(shí)如果沒有指定量詞則匹配其中一個(gè);

3> 字符類的內(nèi)部,除了 \ 之外,其他的特殊符號不在為原來的意思;

4> ^ 放在開頭表示否定,放在其他位置表示自身。

3)速記法

. ------可以匹配換行符之外的任何一個(gè)字符

  • \d ------匹配一個(gè)Unicode數(shù)字
  • \D ------匹配一個(gè)Unicode非數(shù)字
  • \s ------匹配Unicode空白
  • \S ------匹配Unicode非空白
  • \w ------匹配Unicode單詞字符
  • \W ------匹配Unicode非單字符
  • ? ------匹配前面的字符0次或者1次
  • *------匹配前面的字符0次或者多次
  • +(加號)------匹配前面的字符1次或者多次
  • {m} ------匹配前面的表達(dá)式m次
  • {m, } ------匹配前面的表達(dá)式至少m次
  • {, n} ------匹配前面的表達(dá)式最多n次
  • {m, n} ------匹配前面的表達(dá)式至少m次,最多n次
  • () ------捕獲括號內(nèi)部的內(nèi)容

2、Python中的正則表達(dá)式模塊

Python中對于正則表達(dá)式的處理使用的是re模塊,其中的語法可以參加上面所羅列出來的基本語法,尤其應(yīng)該注意一下上述的 3)速記法 中的內(nèi)容。因?yàn)樵谂老x后需要數(shù)據(jù)分析時(shí),往往會(huì)用到上面 3) 速記法 中所羅列出來的那些語法。

3、re模塊的部分方法

1)re.compile()

我們首先在cmd中查看一下 re.compile() 方法的使用方法:

>>> import re
>>> help(re.compile)
Help on function compile in module re:

compile(pattern, flags=0)
    Compile a regular expression pattern, returning a pattern object.

>>>

Compile a regular expression pattern, returning a pattern object.

的意思如下所示:

編譯常規(guī)表達(dá)模式,返回模式對象。

使用re.compile(r, f)方法生成正則表達(dá)式對象,然后調(diào)用正則表達(dá)式對象的相應(yīng)方法。這種做法的好處是生成正則對象之后可以多次使用。

2)re.findall()

同樣的,我們先看help

>>> help(re.findall)
Help on function findall in module re:

findall(pattern, string, flags=0)
    Return a list of all non-overlapping matches in the string.

    If one or more capturing groups are present in the pattern, return
    a list of groups; this will be a list of tuples if the pattern
    has more than one group.

    Empty matches are included in the result.

注意這一段話:

Return a list of all non-overlapping matches in the string.

If one or more capturing groups are present in the pattern, return
a list of groups; this will be a list of tuples if the pattern
has more than one group.

Empty matches are included in the result.

意思是說:

re.findall(s,start, end)

返回一個(gè)列表,如果正則表達(dá)式中沒有分組,則列表中包含的是所有匹配的內(nèi)容,
如果正則表達(dá)式中有分組,則列表中的每個(gè)元素是一個(gè)元組,元組中包含子分組中匹配到的內(nèi)容,但是沒有返回整個(gè)正則表達(dá)式匹配的內(nèi)容。

3)re.finditer()

>>> help(re.finditer)
Help on function finditer in module re:

finditer(pattern, string, flags=0)
    Return an iterator over all non-overlapping matches in the
    string.  For each match, the iterator returns a match object.

    Empty matches are included in the result.

re.finditer(s, start, end)

返回一個(gè)可迭代對象

對可迭代對象進(jìn)行迭代,每一次返回一個(gè)匹配對象,可以調(diào)用匹配對象的group()方法查看指定組匹配到的內(nèi)容,0表示整個(gè)正則表達(dá)式匹配到的內(nèi)容

4) re.search()

>>> help(re.search)
Help on function search in module re:

search(pattern, string, flags=0)
    Scan through string looking for a match to the pattern, returning
    a match object, or None if no match was found.

re.search(s, start, end)

返回一個(gè)匹配對象,倘若沒匹配到,就返回None

search方法只匹配一次就停止,不會(huì)繼續(xù)往后匹配

5)re.match()

>>> help(re.match)
Help on function match in module re:

match(pattern, string, flags=0)
    Try to apply the pattern at the start of the string, returning
    a match object, or None if no match was found.

re.match(s, start, end)

如果正則表達(dá)式在字符串的起始處匹配,就返回一個(gè)匹配對象,否則返回None

6) re.sub()

>>> help(re.sub)
Help on function sub in module re:

sub(pattern, repl, string, count=0, flags=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it's passed the match object and must return
    a replacement string to be used.

re.sub(x, s, m)

返回一個(gè)字符串。每一個(gè)匹配的地方用x進(jìn)行替換,返回替換后的字符串,如果指定m,則最多替換m次。對于x可以使用/i或者/gid可以是組名或者編號來引用捕獲到的內(nèi)容。

模塊方法re.sub(r, x, s, m)中的x可以使用一個(gè)函數(shù)。此時(shí)我們就可以對捕獲到的內(nèi)容推過這個(gè)函數(shù)進(jìn)行處理后再替換匹配到的文本。

7) re.subn()

>>> help(re.subn)
Help on function subn in module re:

subn(pattern, repl, string, count=0, flags=0)
    Return a 2-tuple containing (new_string, number).
    new_string is the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in the source
    string by the replacement repl.  number is the number of
    substitutions that were made. repl can be either a string or a
    callable; if a string, backslash escapes in it are processed.
    If it is a callable, it's passed the match object and must
    return a replacement string to be used.

rx.subn(x, s, m)

與re.sub()方法相同,區(qū)別在于返回的是二元組,其中一項(xiàng)是結(jié)果字符串,一項(xiàng)是做替換的個(gè)數(shù)

8) re.split()

>>> help(re.split)
Help on function split in module re:

split(pattern, string, maxsplit=0, flags=0)
    Split the source string by the occurrences of the pattern,
    returning a list containing the resulting substrings.  If
    capturing parentheses are used in pattern, then the text of all
    groups in the pattern are also returned as part of the resulting
    list.  If maxsplit is nonzero, at most maxsplit splits occur,
    and the remainder of the string is returned as the final element
    of the list.

re.split(s, m)

分割字符串,返回一個(gè)列表,用正則表達(dá)式匹配到的內(nèi)容對字符串進(jìn)行分割

如果正則表達(dá)式中存在分組,則把分組匹配到的內(nèi)容放在列表中每兩個(gè)分割的中間作為列表的一部分

三、正則表達(dá)式使用的實(shí)例

我們就爬一個(gè)蟲來進(jìn)行正則表達(dá)式的使用吧:

爬取豆瓣電影的Top250榜單并且獲取到每一部電影的相應(yīng)評分。

import re
import requests
if __name__ == '__main__':
    """
    測試函數(shù)(main)
    """
    N = 25
    j = 1
    for i in range(0, 226, 25):
        url = f'https://movie.douban.com/top250?start={i}&filter='
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                          '(KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63'
        }
        response = requests.get(url=url, headers=headers)
        result = re.findall(r'<a href="(\S+)">\s+'
                            r'<img width="100" alt="(\S+)" src="\S+" class="">\s+'
                            r'</a>', response.text)
        for movie in result:
            url_0 = movie[0]
            response_0 = requests.get(url=url_0, headers=headers)
            score = re.findall(r'<strong class="ll rating_num" property="v:average">(\S+)'
                               r'</strong>\s+'
                               r'<span property="v:best" content="10.0"></span>',
                               response_0.text)[0]
            print(j, end='  ')
            j += 1
            print(movie[1], end='  ')
            print(movie[0], end='  ')
            print(f'評分 : {score}')
        i += N

在這里,我們的正則表達(dá)式用來提取了電影名稱、電影的url鏈接,然后再通過訪問電影的url鏈接進(jìn)入電影的主頁并獲取到電影的評分信息。
主要的正則表達(dá)式使用代碼為:

1、獲取電影名稱以及電影url:

result = re.findall(r'<a href="(\S+)">\s+'
                            r'<img width="100" alt="(\S+)" src="\S+" class="">\s+'
                            r'</a>', response.text)

2、獲取電影的相應(yīng)評分:

score = re.findall(r'<strong class="ll rating_num" property="v:average">(\S+)'
                               r'</strong>\s+'
                               r'<span property="v:best" content="10.0"></span>',
                               response_0.text)[0]

最后我們需要再說一下,這里爬蟲的美中不足的地方就是這個(gè)接口似乎不能夠爬取到250了,只能爬取到248個(gè)電影,這個(gè)應(yīng)該只是接口的問題,但是影響不是很大啦。

如下圖所示:

正則表達(dá)式的簡介我也就寫到這里就結(jié)束了啦,希望對大家有所幫助啦。

當(dāng)然我為了寫這篇博文中的豆瓣爬蟲,已經(jīng)被豆瓣封了;

至于 403 錯(cuò)誤是因?yàn)椋涸L問的端口被禁止,或者原來的端口被修改所致。

這里顯然是我被禁止了。

總結(jié)

到此這篇關(guān)于Python正則表達(dá)式re模塊講解以及其案例舉例的文章就介紹到這了,更多相關(guān)Python re模塊案例內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • django框架cookie和session用法實(shí)例詳解

    django框架cookie和session用法實(shí)例詳解

    這篇文章主要介紹了django框架cookie和session用法,結(jié)合實(shí)例形式詳細(xì)分析了Django框架cookie和session的功能、原理、使用方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下
    2019-12-12
  • Python標(biāo)準(zhǔn)庫之日期、時(shí)間和日歷模塊

    Python標(biāo)準(zhǔn)庫之日期、時(shí)間和日歷模塊

    這篇文章介紹了Python標(biāo)準(zhǔn)庫之日期、時(shí)間和日歷模塊,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-05-05
  • Python編寫運(yùn)維進(jìn)程文件目錄操作實(shí)用腳本示例

    Python編寫運(yùn)維進(jìn)程文件目錄操作實(shí)用腳本示例

    這篇文章主要為大家介紹了Python編寫實(shí)用運(yùn)維進(jìn)程文件目錄的操作腳本示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05
  • python函數(shù)中將變量名轉(zhuǎn)換成字符串實(shí)例

    python函數(shù)中將變量名轉(zhuǎn)換成字符串實(shí)例

    這篇文章主要介紹了python函數(shù)中將變量名轉(zhuǎn)換成字符串實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • python實(shí)現(xiàn)比較類的兩個(gè)instance(對象)是否相等的方法分析

    python實(shí)現(xiàn)比較類的兩個(gè)instance(對象)是否相等的方法分析

    這篇文章主要介紹了python實(shí)現(xiàn)比較類的兩個(gè)instance(對象)是否相等的方法,結(jié)合實(shí)例形式分析了Python判斷類的實(shí)例是否相等的判斷操作實(shí)現(xiàn)技巧,需要的朋友可以參考下
    2019-06-06
  • python中利用zfill方法自動(dòng)給數(shù)字前面補(bǔ)0

    python中利用zfill方法自動(dòng)給數(shù)字前面補(bǔ)0

    python中有一個(gè)zfill方法用來給字符串前面補(bǔ)0,非常不錯(cuò),下面小編給大家分享了實(shí)例代碼,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧
    2018-04-04
  • DRF之請求與響應(yīng)的實(shí)現(xiàn)

    DRF之請求與響應(yīng)的實(shí)現(xiàn)

    本文主要介紹了DRF請求與響應(yīng)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-07-07
  • python中用ggplot繪制畫圖實(shí)例講解

    python中用ggplot繪制畫圖實(shí)例講解

    在本篇文章里小編給大家整理的是一篇關(guān)于python中用ggplot繪制畫圖實(shí)例講解內(nèi)容,有興趣的朋友們可以學(xué)習(xí)參考下。
    2021-01-01
  • Python+matplotlib繪制餅圖和堆疊圖

    Python+matplotlib繪制餅圖和堆疊圖

    Matplotlib是Python的繪圖庫,它能讓使用者很輕松地將數(shù)據(jù)圖形化,并且提供多樣化的輸出格式。本文將為大家介紹如何用matplotlib繪制餅圖和堆疊圖,感興趣的朋友可以學(xué)習(xí)一下
    2022-04-04
  • Python中Pyenv virtualenv插件的使用

    Python中Pyenv virtualenv插件的使用

    pyenv是管理python版本的工具。安裝pyenv后,可以管理各種python版本,并且各個(gè)版本的環(huán)境完全獨(dú)立,互不干擾。今天通過本文給大家分享Python中Pyenv virtualenv插件的使用,感興趣的朋友一起看看吧
    2021-06-06

最新評論

余江县| 喀喇| 五常市| 兴宁市| 望城县| 万年县| 石家庄市| 台中县| 桂平市| 阿拉善右旗| 扬州市| 马关县| 高青县| 侯马市| 新津县| 邮箱| 阳谷县| 彭阳县| 清水河县| 中山市| 东光县| 桂东县| 左贡县| 镇沅| 光泽县| 灵丘县| 庄河市| 邳州市| 灵川县| 富民县| 运城市| 新泰市| 青川县| 荥经县| 社会| 濮阳市| 新兴县| 炎陵县| 华安县| 长沙县| 泰和县|