只是清空''或什么都没有

,python,html,regex,python-3.x,beautifulsoup"/>

首页 > 解决方案 > 将字符串中的值替换为类似

只是清空''或什么都没有

问题描述

我有一个 BeautifulSoup 段落作为字符串。我想使用正则表达式替换字符串中p(开始)和/p(结束)标签的出现,因为有像这样的实例

    <p class="section-para">We would be happy to hear from you, Please 
    fill in the form below or mail us your requirements on<br/><span 
    class="text-red">contact@xyz.com</span></p> 

但我不能使用泛型

    ^< *>$

因为我想要strong , bh1,h1..h6用于不同目的的标签。

我只知道 RegEx 的基础知识,但不知道如何制作和使用。有人可以帮我制作“包含”、“排除”(如果有的话)。我怎样才能为这个问题做一个,我怎样才能用简单的 ''

def formatting(string):
    this=['<h1>','</h1>','<h2>','</h2>','<h3>','</h3>','<h4>','</h4>','<h5>','</h5>','<h6>','</h6>','<b>','</b>','<strong>','</strong>']
    with_this=['\nh1 Tag:','\n','\nh2 Tag:','\n''\nh3 Tag:','\n''\nh4 Tag:','\n''\nh5 Tag:','\n''\nh6 Tag:','\n','\Bold:','\n''\nBold:','\n']

    for i in range(len(this)):
        if this[i] in string:
            string=string.replace(this[i],with_this[i])
    return(string)

我已经为h1,2...6标签使用了字符串的替换功能。任何帮助,将不胜感激。

标签: pythonhtmlregexpython-3.xbeautifulsoup

解决方案


目前尚不清楚您要替换的确切内容,但也许以下内容可以提供帮助,如果您需要的话,它将允许您用文本替换标签。相信您将能够进一步调整以使其达到您想要的效果。此外,您没有指定您正在使用的 BS 版本。我正在使用BS4。该函数将接受一个美丽的汤对象,一个要查找的标签,一个前缀 IE 你想用什么替换开始标签和一个后缀 IE 你想用什么替换结束标签。

from bs4 import BeautifulSoup

def format_soup_tag(soup, tag, prefix, suffix):
    target_tag = soup.find(tag)
    target_tag.insert_before(prefix)
    target_tag.insert_after(suffix)
    target_tag.unwrap()

html = '<p class ="section-para">We would be happy to hear from you, <strong>Please fill in the form below</strong> or mail us your requirements on <br/><span class ="text-red" >contact@xyz.com</span></p>'
soup = BeautifulSoup(html, features="lxml")
print("###before modification###\n", soup, "\n")

format_soup_tag(soup, 'p', '\np tag: ', '\n')
print("###after p tag###\n", soup, "\n")

format_soup_tag(soup, 'strong', '\Bold: ', ' \Bold')
print("###after strong tag###\n", soup, "\n")

输出

###before modification###
 <html><body><p class="section-para">We would be happy to hear from you, <strong>Please fill in the form below</strong> or mail us your requirements on <br/><span class="text-red">contact@xyz.com</span></p></body></html> 

###after p tag###
 <html><body>
p tag: We would be happy to hear from you, <strong>Please fill in the form below</strong> or mail us your requirements on <br/><span class="text-red">contact@xyz.com</span>
</body></html> 

###after strong tag###
 <html><body>
p tag: We would be happy to hear from you, \Bold: Please fill in the form below \Bold or mail us your requirements on <br/><span class="text-red">contact@xyz.com</span>
</body></html> 

推荐阅读