python - 将字符串中的值替换为类似
只是清空''或什么都没有
问题描述
我有一个 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 , b和h1,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标签使用了字符串的替换功能。任何帮助,将不胜感激。
解决方案
目前尚不清楚您要替换的确切内容,但也许以下内容可以提供帮助,如果您需要的话,它将允许您用文本替换标签。相信您将能够进一步调整以使其达到您想要的效果。此外,您没有指定您正在使用的 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>
推荐阅读
- makefile - 如何在 makefile 中使用 g++ 编译位于不同目录中的源文件和头文件?
- visual-studio - 如何使代码抑制消息始终以英文显示?
- mathematical-optimization - N个产品与M个特征的最优组合
- angular - 为什么我在使用 Microsoft Graph REST API 使用 Angular 调用此端点时会收到 403 禁止响应?
- r - R,data.table - 为多个表创建新列
- mpesa - Safaricom 仪表板未显示所有测试凭据
- java - 执行 SonarScanner.MSBuild.exe end 命令后执行 SonarScanner 期间出错
- javascript - Javascript如何生成时隙的动态列表
- javascript - 有没有办法在 for 中定义一个钩子?
- grafana - InfluxQL 数据源连接错误“xxxxxx....” 找不到数据库