如何删除python中某个单词周围的括号

2024-10-01 22:33:46 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我正在尝试制作一个代码,每当“div”一词出现在尖括号之间时,该代码就会删除尖括号

<div class="ipc-page-content-container ipc-page-content-container--center" role="presentation"><a class="ipc-button ipc-button--double-padding ipc-button--default-height ipc-button--core-baseAlt ipc-button--theme-baseAlt ipc-button imdb-footer__open-in-app-button" href="/whitelist-offsite?url=https%3A%2F%2Ftqp-4.tlnk.io%2Fserve%3Faction%3Dclick%26campaign_id_android%3D427112%26campaign_id_ios%3D427111%26destination_id_android%3D464200%26destination_id_ios%3D464199%26my_campaign%3Dmdot%2520sitewide%2520footer%2520%26my_site%3Dm.imdb.com%26publisher_id%3D350552%26site_id_android%3D133429%26site_id_ios%3D133428&amp;page-action=ft-gettheapp&amp;ref=ft_apps" tabindex="0"><div class="ipc-button__text">Get the IMDb App</div></a></div></div><div class="ipc-page-content-container ipc-page-content-container--center _2AR8CsLqQAMCT1_Q7eidSY" role="presentation">

例如,当使用此代码时,<div class="ipc-page-content-container ipc-page-content-container--center" role="presentation">将变成div class="ipc-page-content-container ipc-page-content-container--center" role="presentation"

我尝试使用正则表达式在文本中查找div,但似乎找不到删除尖括号的方法

import re
with open("movie.text.txt", 'rt', encoding='UTF8') as myfile:
    text = myfile.read()

    regex = "<div .+>"

    text = re.sub(regex, "div .+", text)

这段代码似乎删除了文本的每一行,只需将其替换为div .+ 有人知道如何使这段代码正常工作吗


Tags: 代码textdividcontainerpagebuttoncontent
2条回答

一种方法是:

regex = "<div .+>"

def matched(matchobj):
    return matchobj.group(0)[1:-1]

text = re.sub(regex, matched, text)

这为re.sub()提供了一个回调函数,对每个匹配项调用该函数并返回替换字符串。在这个替换字符串中,我们只对字符串的第一个和最后一个字符进行切片

matchobj.group(0)将返回整个匹配字符串

字符串的简单名称。替换(“>;”或“<;”,”)应该可以。“”没有任何含义,因此它们都将被替换为零。如果这一行不行,只需拆分or语句,然后一次做一个尖括号字符串名称。替换('>;','')然后对另一个角括号执行相同操作

相关问题 更多 >

    热门问题