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

如何使用Python中的正則表達式處理html文件

 更新時間:2023年04月28日 12:40:40   作者:the?only?KIrsTEN  
html類型的文本數(shù)據(jù)內(nèi)容是由前端代碼書寫的標簽+文本數(shù)據(jù)的格式,可以直接在chrome瀏覽器打開,清楚的展示出文本的格式,下面這篇文章主要給大家介紹了關于如何使用Python中的正則表達式處理html文件的相關資料,需要的朋友可以參考下

使用Python中的正則表達式處理html文件

finditer方法是一種全匹配方法。您可能已經(jīng)使用了findall方法,它返回多個匹配字符串的列表。finditer返回一個迭代器順序地為多個匹配中的每一個生成匹配對象。在下面的代碼中,這些匹配對象被訪問(通過for循環(huán)),因此可以打印組1。

您的任務是編寫Python RE來識別HTML文本文件中的某些模式。將代碼添加到STARTER腳本為這些模式編譯RE(將它們分配給有意義的變量名稱),并將這些RE應用于文件的每一行,打印出找到的匹配項。

1.編寫識別HTML標簽的模式,然后將其打印為“TAG:TAG string”(例如“TAG:b”代表標簽)。為了簡單起見,假設左括號和右括號每個標記的(<,>)將始終出現(xiàn)在同一行文本中。第一次嘗試可能使regex“<.*>”其中“.”是與任何字符匹配的預定義字符類符號。嘗試找出這一點,找出為什么這不是一個好的解決方案。編寫一個更好的解決方案,解決這個問題

2.修改代碼,使其區(qū)分開頭和結尾標記(例如p與/p)打印OPENTAG和CLOSETAG

import sys, re

#------------------------------

testRE = re.compile('(logic|sicstus)', re.I)
testI = re.compile('<[A-Za-z]>', re.I)
testO = re.compile('<[^/](\S*?)[^>]*>')
testC = re.compile('</(\S*?)[^>]*>')

with open('RGX_DATA.html') as infs: 
    linenum = 0
    for line in infs:
        linenum += 1
        if line.strip() == '':
            continue
        print('  ', '-' * 100, '[%d]' % linenum, '\n   TEXT:', line, end='')
    
        m = testRE.search(line)
        if m:
            print('** TEST-RE:', m.group(1))

        mm = testRE.finditer(line)
        for m in mm:
            print('** TEST-RE:', m.group(1))
        
        index= testI.finditer(line)
        for i in index:
           print('Tag:',i.group().replace('<', '').replace('>', ''))
           
        open1= testO.finditer(line)
        for m in open1:
           print('opening:',m.group().replace('<', '').replace('>', ''))
           
        close1= testC.finditer(line)
        for n in close1:
           print('closing:',n.group().replace('<', '').replace('>', ''))

請注意,有些HTML標簽有參數(shù),例如:

<table border=1 cellspacing=0 cellpadding=8>

確保打開標記的模式適用于帶參數(shù)和不帶參數(shù)的標記,即成功找到并打印標簽標簽?,F(xiàn)在擴展您的代碼,以便打印兩個打開的標簽標簽和參數(shù),例如:

OPENTAG: table
PARAM: border=1
PARAM: cellspacing=0
PARAM: cellpadding=8

 		open1= testO.finditer(line)
        for m in open1:
            #print('opening:',m.group().replace('<', '').replace('>', ''))
            firstm= m.group().replace('<', '').replace('>', '').split()
            num = 0
            for otherm in firstm:
                if num == 0:
                    print('opening:',otherm)
                else:
                    print('pram:',otherm)
                num+= 1

在正則表達式中,可以使用反向引用來指示匹配早期部分的子字符串,應再次出現(xiàn)正則表達式的。格式為\N(其中N為正整數(shù)),并返回到第N個匹配的文本正則表達式組。例如,正則表達式,如:r" (\w+) \1 僅當與組(\w+)完全匹配的字符串再次出現(xiàn)時才匹配 backref\1出現(xiàn)的位置。這可能與字符串“踢”匹配.例如,“the”出現(xiàn)兩次。使用反向引用編寫一個模式,當一行包含成對的open和關閉標簽,例如在粗體中.

考慮到我們可能想要創(chuàng)建一個執(zhí)行HTML剝離的腳本,即一個HTML文件,并返回一個純文本文件,所有HTML標記都已從中刪除出來這里我們不打算這樣做,而是考慮一個更簡單的例子,即刪除我們在輸入數(shù)據(jù)文件的任何行中找到的HTML標記。

你應該能夠讓您已經(jīng)定義的RE識別HTML標簽這樣做,將生成的文本打印到屏幕上為STRIPPED:。。

import sys, re

#------------------------------
# PART 1: 

   # Key thing is to avoid matching strings that include
   # multiple tags, e.g. treating '<p><b>' as a single
   # tag. Can do this in several ways. Firstly, use
   # non-greedy matching, so get shortest possible match
   # including the two angle brackets:

tag = re.compile('</?(.*?)>') 

   # The above treats the '/' of a close tag as a separate
   # optional component - so that this doesn't turn up as
   # part of the match '.group(1)', which is meant to return
   # the tag label. 
   # Following alternative solution uses a negated character
   # class to explicitly prevent this including '>': 

tag = re.compile('</?([^>]+)>') 

   # Finally, following version separates finding the tag
   # label string from any (optional) parameters that might
   # also appear before the close angle bracket:

tag = re.compile(r'</?(\w+\b)([^>]+)?>') 

   # Note that use of '\b' (as word boundary anchor) here means
   # we must mark the regex string as a 'raw' string (r'..'). 

#------------------------------
# PART 2: 

   # Following closeTag definition requires first first char
   # after the open angle bracket to be '/', while openTag
   # definition excludes this by requiring first char to be
   # a 'word char' (\w):

openTag  = re.compile(r'<(\w[^>]*)>')
closeTag = re.compile(r'</([^>]*)>')

   # Following revised definitions are more carefully stated
   # for correct extraction of tag label (separately from
   # any parameters:

openTag  = re.compile(r'<(\w+\b)([^>]+)?>')
closeTag = re.compile(r'</(\w+\b)\s*>')

#------------------------------
# PART 3: 

   # Above openTag definition will already get the string
   # encompassing any parameters, and return it as
   # m.group(2), i.e. defn: 

openTag  = re.compile(r'<(\w+\b)([^>]+)?>')

   # If assume that parameters are continuous non-whitespace
   # chars separated by whitespace chars, then we can divide
   # them up using split - and that's how we handle them
   # here. (In reality, parameter strings can be a lot more
   # messy than this, but we won't try to deal with that.)

#------------------------------
# PART 4: 

openCloseTagPair = re.compile(r'<(\w+\b)([^>]+)?>(.*?)</\1\s*>')

   # Note use of non-greedy matching for the text falling
   # *between* the open/close tag pair - to avoid false
   # results where have two similar tag pairs on same line.

#------------------------------
# PART 5: URLS

   # This is quite tricky. The URL expressions in the file
   # are of two kinds, of which the first is a string
   # between double quotes ("..") which may include
   # whitespace. For this case we might have a regex: 

url = re.compile('href=("[^">]+")', re.I)

   # The second case does not have quotes, and does not
   # allow whitespace, consisting of a continuous sequence
   # of non-whitespace material (that ends when you reach a
   # space or close bracket '>'). This might be: 

url = re.compile('href=([^">\s]+)', re.I)

   # We can combine these two cases as follows, and still
   # get the expression back as group(1):

url = re.compile(r'href=("[^">]+"|[^">\s]+)', re.I)

   # Note that I've done nothing here to exclude 'mailto:'
   # links as being accepted as URLS. 

#------------------------------

with open('RGX_DATA.html') as infs: 
    linenum = 0
    for line in infs:
        linenum += 1
        if line.strip() == '':
            continue
        print('  ', '-' * 100, '[%d]' % linenum, '\n   TEXT:', line, end='')
    
        # PART 1: find HTML tags
        # (The following uses 'finditer' to find ALL matches
        # within the line)
    
        mm = tag.finditer(line)
        for m in mm:
            print('** TAG:', m.group(1), ' + [%s]' % m.group(2))
    
        # PART 2,3: find open/close tags (+ params of open tags)
    
        mm = openTag.finditer(line)
        for m in mm:
            print('** OPENTAG:', m.group(1))
            if m.group(2):
                for param in m.group(2).split():
                    print('    PARAM:', param)
    
        mm = closeTag.finditer(line)
        for m in mm:
            print('** CLOSETAG:', m.group(1))
    
        # PART 4: find open/close tag pairs appearing on same line
    
        mm = openCloseTagPair.finditer(line)
        for m in mm:
            print("** PAIR [%s]: \"%s\"" % (m.group(1), m.group(3)))
    
        # PART 5: find URLs:
    
        mm = url.finditer(line)
        for m in mm:
            print('** URL:', m.group(1))

        # PART 6: Strip out HTML tags (note that .sub will do all
        # possible substitutions, unless number is limited by count
        # keyword arg - which is fortunately what we want here)

        stripped = tag.sub('', line)
        print('** STRIPPED:', stripped, end = '') 

總結

到此這篇關于如何使用Python中的正則表達式處理html文件的文章就介紹到這了,更多相關Python正則處理html文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Python2和Python3的共存和切換使用

    Python2和Python3的共存和切換使用

    這篇文章主要介紹了Python2和Python3的共存和切換使用,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-04-04
  • Python使用pathlib進行文件系統(tǒng)操作

    Python使用pathlib進行文件系統(tǒng)操作

    pathlib?是?Python?的一個標準庫,它提供了一個面向?qū)ο蟮奈募到y(tǒng)路徑操作接口,本文主要介紹了Python使用pathlib進行文件系統(tǒng)操作的相關知識,有需要的可以了解下
    2024-11-11
  • Python selenium模塊實現(xiàn)定位過程解析

    Python selenium模塊實現(xiàn)定位過程解析

    這篇文章主要介紹了python selenium模塊實現(xiàn)定位過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-07-07
  • Python檢測生僻字的實現(xiàn)方法

    Python檢測生僻字的實現(xiàn)方法

    最近在工作中碰到一個需求,要求檢測字段是否包含生僻字以及一些非法字符如 ~!@#$%^&*。通過網(wǎng)上的查找資料解決了,現(xiàn)在將解決的過程和示例代碼分享給大家,有需要的可以參考借鑒。下面來一起看看吧。
    2016-10-10
  • python函數(shù)參數(shù)*args**kwargs用法實例

    python函數(shù)參數(shù)*args**kwargs用法實例

    python當函數(shù)的參數(shù)不確定時,可以使用*args和**kwargs。*args沒有key值,**kwargs有key值,下面看例子
    2013-12-12
  • 吳恩達機器學習練習:神經(jīng)網(wǎng)絡(反向傳播)

    吳恩達機器學習練習:神經(jīng)網(wǎng)絡(反向傳播)

    這篇文章主要介紹了學習吳恩達機器學習中的一個練習:神經(jīng)網(wǎng)絡(反向傳播),在這個練習中,你將實現(xiàn)反向傳播算法來學習神經(jīng)網(wǎng)絡的參數(shù),需要的朋友可以參考下
    2021-04-04
  • Python中數(shù)據(jù)解壓縮的技巧分享

    Python中數(shù)據(jù)解壓縮的技巧分享

    在日常的數(shù)據(jù)處理和分析中,經(jīng)常會遇到需要對壓縮數(shù)據(jù)進行解壓縮的情況,本文主要來和大家分享一下Python中數(shù)據(jù)解壓縮的相關技巧,希望對大家有所幫助
    2024-03-03
  • python實現(xiàn)操作文件(文件夾)

    python實現(xiàn)操作文件(文件夾)

    這篇文章主要為大家詳細介紹了pyhton實現(xiàn)操作文件、操作文件夾,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-10-10
  • 如何利用Python動態(tài)展示排序算法

    如何利用Python動態(tài)展示排序算法

    Python是一種簡單易學,功能強大的編程語言,它有高效率的高層數(shù)據(jù)結構,能夠簡單、有效地實現(xiàn)面向?qū)ο缶幊?下面這篇文章主要給大家介紹了關于如何利用Python動態(tài)展示排序算法的相關資料,需要的朋友可以參考下
    2021-10-10
  • 淺談django不使用restframework自定義接口與使用的區(qū)別

    淺談django不使用restframework自定義接口與使用的區(qū)別

    這篇文章主要介紹了淺談django不使用restframework自定義接口與使用的區(qū)別,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07

最新評論

孝昌县| 韶关市| 宿迁市| 朝阳区| 莱芜市| 宁强县| 武乡县| 泗水县| 太康县| 邻水| 英吉沙县| 康平县| 三都| 朔州市| 浑源县| 景东| 佛学| 东乡族自治县| 醴陵市| 文成县| 永靖县| 大竹县| 安丘市| 偏关县| 资源县| 永泰县| 蒙自县| 科技| 团风县| 营口市| 剑阁县| 乌拉特后旗| 南宫市| 崇仁县| 南川市| 津南区| 温州市| 玉林市| 思南县| 双鸭山市| 渭南市|