当前位置:

首页 > 编程开发 > Python 正则表达式处理 HTML 文件的实现方法

Python 正则表达式处理 HTML 文件的实现方法

使用Python中的正则表达式处理html文件finditer方法是一种全匹配方法。您可能已经使用了findall方法,它返回多个匹配字符串的列表。finditer返回一个迭代器顺序地为多个匹配中的每一个生成匹配对象。在下面的代码中,这些匹配对象被访问(通过for循环),因此可以打印组1。您的任务是编写PythonRE来识别HTML文本文件中的某些模式。将代码添加到STARTER脚本为这些模式编译RE(将它们分配给有意义的变量名称),并将这些RE应用于文件的每一行,打印出找到的匹配项。1.编写识别HTML

使用Python中的正则表达式处理html文件

finditer方法是一种全匹配方法。您可能已经使用了findall方法,它返回多个匹配字符串的列表。finditer返回一个迭代器顺序地为多个匹配中的每一个生成匹配对象。在下面的代码中,这些匹配对象被访问(通过for循环),因此可以打印组1。

您的任务是编写Python RE来识别HTML文本文件中的某些模式。将代码添加到STARTER脚本为这些模式编译RE(将它们分配给有意义的变量名称),并将这些RE应用于文件的每一行,打印出找到的匹配项。

1.编写识别HTML标签的模式,然后将其打印为“TAG:TAG string”(例如“TAG:b”代表标签)。为了简单起见,假设左括号和右括号每个标记的(<,>)将始终出现在同一行文本中。第一次尝试可能使regex“<.*>”其中“.”是与任何字符匹配的预定义字符类符号。尝试找出这一点,找出为什么这不是一个好的解决方案。编写一个更好的解决方案,解决这个问题

2.修改代码,使其区分开头和结尾标记(例如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(']*>')

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标签有参数,例如:

确保打开标记的模式适用于带参数和不带参数的标记,即成功找到并打印标签标签。现在扩展您的代码,以便打印两个打开的标签标签和参数,例如:

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

在正则表达式中,可以使用反向引用来指示匹配早期部分的子字符串,应再次出现正则表达式的。格式为\N(其中N为正整数),并返回到第N个匹配的文本正则表达式组。例如,正则表达式,如:r" (\w+) \1 仅当与组(\w+)完全匹配的字符串再次出现时才匹配 backref\1出现的位置。这可能与字符串“踢”匹配.例如,“the”出现两次。使用反向引用编写一个模式,当一行包含成对的open和关闭标签,例如在粗体中.

考虑到我们可能想要创建一个执行HTML剥离的脚本,即一个HTML文件,并返回一个纯文本文件,所有HTML标记都已从中删除出来这里我们不打算这样做,而是考虑一个更简单的例子,即删除我们在输入数据文件的任何行中找到的HTML标记。

你应该能够让您已经定义的RE识别HTML标签这样做,将生成的文本打印到屏幕上为STRIPPED:。。

import sys, re

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

   # Key thing is to avoid matching strings that include
   # multiple tags, e.g. treating '

' 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']+)?>')     # 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'') #------------------------------ # 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)([^>]+)?>(.*?)')    # 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
相关文章 更多
Python安装后怎么打开:使用IDLE或命令行启动解释器
Python安装后怎么打开:使用IDLE或命令行启动解释器

刚在Windows安装好Python却不知道如何启动?本文详细演示如何通过开始菜单找到并打开IDLE集成开发环境,以及如何在PowerShell或命令提示符中使用python和py命令启动交互式解释器、运行.py脚本文件。包含退出解释器的方法及常见启动问题排查,帮助初学者快速验证安装成功并开始编写代码。

Windows系统Python安装教程:下载、勾选PATH及环境变量配置
Windows系统Python安装教程:下载、勾选PATH及环境变量配置

针对Windows初学者的Python安装实战指南。详细讲解如何从Python官网下载匹配架构的安装包,重点演示安装首屏勾选“Add python.exe to PATH”的关键操作,并提供使用python --version和py命令验证环境变量的具体步骤,帮助新手快速搭建开发环境并排查路径问题。

麒麟OS如何查看Python进程的运行状态
麒麟OS如何查看Python进程的运行状态

要想确认麒麟OS中Python程序的运行状态以及资源占用情况,我们可以这样做:用ps -ef | grep python来筛选进程;通过top命令,按P键排序查看实时负载;使用pgrep -f "script.py"精准获取PID;借助lsof -p PID验证文件打开状态。另外,还可以结合syst

Python在Debian上如何配置SSL证书
Python在Debian上如何配置SSL证书

在Debian系统上配置SSL证书通常涉及以下几个步骤:安装Web服务器:首先,你需要一个Web服务器,比如Apache或Nginx。这里以Apache为例。sudo apt updatesudo apt install apache2获取SSL证书:你可以从Let’s Encrypt免费获取SSL

统信UOS怎么安装Python开发环境
统信UOS怎么安装Python开发环境

要想让Python项目在统信UOS上正常运行,得先安装python3、python3-pip、python3-venv、python3-dev以及build-essential等组件。具体操作就是执行sudo apt install命令来一步到位完成安装,同时别忘了配置清华镜像源来给pip加速哦。在

纯Python方案实现中英文全文搜索
纯Python方案实现中英文全文搜索

在互联网上的各类网站中,无论大小,基本上都会有一个搜索框,用来给用户对内容进行搜索,小到站点搜索,大到搜索引擎搜索。从简单的来说,搜索功能确实很简单,一个简单的select语句就可以实现数据的搜索。而从复杂的来看,无论是搜索的精度还是搜索的效率,都是有很深的研究范围的。对于简单的搜索功能来说,一个s

Mac如何取消通过Python脚本运行的关机程序
Mac如何取消通过Python脚本运行的关机程序

立即在终端输入sudo shutdown -c取消倒计时关机,成功后显示“Shutdown cancelled”;若存在pmset重复任务,需再执行sudo pmset repeat cancel清除。Mac因Python脚本执行了os.system("sudo shutdown -h +10")或

PS网页版直接使用
PS网页版直接使用

PS网页版免费官方入口为https://www.adobe.com/products/photoshop/web.html,支持PSD编辑、实时协作、多色彩空间、智能抠图、AI修复、跨端同步、中文引导及SVG/PSD兼容等核心功能。 对于很多设计新手,或者只是偶尔需要处理图片的朋友来说,直接在线、免

淘宝网页版入口查找教程
淘宝网页版入口查找教程

淘宝官方网页登录入口 对于如何找到淘宝网页版的入口,很多朋友都感到有点摸不着头脑。别急,这篇文章就来为你拆解清楚整个登录流程。官方的登录入口很明确,就在官网首页的左上角。 淘宝网页版入口位于官网首页左上角,点击“亲,请登录”即可跳转至统一的验证页面。登录支持密码、短信验证码和手机APP扫码三种方式,

怎样在无忧小说网中查看阅读进度
怎样在无忧小说网中查看阅读进度

在无忧小说网,如何精准掌握你的阅读进度? 在无忧小说网追更小说,最怕的就是忘了上次读到哪儿。如果感觉界面没有清晰显示阅读进度,别急,这通常不是数据丢失,而是相关视图功能没有开启或找到。掌握下面这四条路径,你就能对阅读进度了如指掌。 一、通过阅读页面顶部状态栏查看 最简单直接的方法,其实就藏在眼皮底下

查看更多
精品专题 更多
装机必备
装机必备

正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

Windows
Windows

正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

macOS软件
macOS软件

正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

Mac软件 更多
灵活计算器
灵活计算器
macOS/iOS/Android

灵活计算器是一款笔记式算数应用,支持实时计算、动态关联和云端同步功能。记录、整理和输出之间的过渡会更自然,适合长期写作、做笔记或持续沉淀个人内容。

赤友清理大师
赤友清理大师
macOS

赤友清理大师是一款为 Mac 设计的智能清理优化工具,可精准扫描垃圾、大文件、重复文件等,释放磁盘空间。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

极度公式
极度公式
Windows/macOS/Linux

极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

WINDOWS 更多
Windows 10
Windows 10
Windows

Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。

极度公式
极度公式
Windows/macOS/Linux

极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

密码键盘
密码键盘
Windows/macOS/iOS/Android

密码键盘是一款兼具安全性与便捷性的高效密码管理器。日常使用里的持续防护和信息管理会更突出,适合把安全控制放进长期使用流程中的场景。