当前位置:

首页 > 编程开发 > 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 = '')

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发 Python html
    相关文章 更多
    python删除一个列表里的重复元素的方法与代码示例
    python删除一个列表里的重复元素的方法与代码示例

    学习如何使用Python高效删除列表中的重复元素。本文提供5种常见方法的代码示例,涵盖保持顺序与不保持顺序的场景,适合初学者和进阶开发者参考。

    Python写接口的步骤及完整代码示例
    Python写接口的步骤及完整代码示例

    详细讲解使用Python编写Web接口的核心步骤与完整代码示例,涵盖环境准备、路由定义、数据校验、服务启动及调试测试方法。

    codex怎么读取word文档及docx文件操作教程
    codex怎么读取word文档及docx文件操作教程

    介绍如何利用编程工具读取和解析Word文档(docx格式),涵盖基础文本提取代码示例、结构化数据处理逻辑,以及处理复杂排版时的技术局限与替代方案。

    怎么在Python中调用C语言代码提升性能
    怎么在Python中调用C语言代码提升性能

    详细讲解在Python中调用C语言代码提升性能的完整实践指南,包含原理分析、编译步骤、ctypes与CFFI具体实现、性能对比及常见陷阱。

    Python与C语言的性能差异及底层原理
    Python与C语言的性能差异及底层原理

    深入解析Python与C语言在执行效率上的数量级差异,从编译机制、变量内存布局、动态类型推断到GIL锁,系统阐明底层核心原理。

    Python和C语言哪个更适合编程入门
    Python和C语言哪个更适合编程入门

    客观对比Python与C语言在心智负担、底层机制与学习反馈上的核心差异,提供清晰有据的选择标准与切实的入门学习路径。

    selenium上传文件教程本地文件路径设置方法
    selenium上传文件教程本地文件路径设置方法

    深入解析Selenium处理文件上传的技术细节,涵盖标准HTML控件的路径直接注入法与非标准控件的系统级模拟方案,提供Windows与Linux环境下的路径设置最佳实践及常见异常排查。

    大数据开发语言选型:Java对比Scala与Python的优缺点及适用场景
    大数据开发语言选型:Java对比Scala与Python的优缺点及适用场景

    针对大数据工程场景,系统对比Java、Scala与Python在执行性能、生态结合、开发效率和维护成本上的核心差异,给出清晰的架构选型依据与落地方案。

    langgraph python guide中文入门教程详解
    langgraph python guide中文入门教程详解

    本篇LangGraph Python中文入门教程详解,系统梳理StateGraph状态机定义、节点编写、边与条件路由、检查点持久化(MemorySaver)等核心机制,提供从环境安装到完整循环智能体构建的代码示例与实操指导。

    Windows 安装 Python:从官方入口到虚拟环境的可复现实践
    Windows 安装 Python:从官方入口到虚拟环境的可复现实践

    面向后端开发者,基于 Python 官方文档说明如何在 Windows 上安装 Python、创建 venv 虚拟环境及使用 pip 管理依赖。包含可复制命令、验证方法及工具选择边界,避免常见配置误区。

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

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

    Windows
    Windows

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

    PDF教程
    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    Mac软件 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    Aperty macOS版
    Aperty macOS版
    macOS

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    WINDOWS 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    PixTV 网页版
    PixTV 网页版
    Windows

    PixTV 是一款在浏览器中使用的 AI 视觉内容创作平台,提供图片、视频、音频、文字生成、AI 分镜、局部重绘、提示词反推和无限画布等工具,适合短剧、漫剧、广告及社交媒体内容制作。