假设你有这个字符串:
text = """<p>Bla bla bla.</p><p>Blo blo blo<a
href="http://www.example.com">bli bli</a>.</p><p>blu blu<br>
<span style="font-size: x-small;"><br>
content to remove</span></p>"""
我的目标是删除<span style="font-size: x-small;"><br>content to remove</span>
中的所有内容,以及开始和结束标记。
因此,如果属性样式为"font-size: x-small;"
,我只能删除span标记(及其内容)。
我的代码不能工作。这就是它:
import re
pattern = re.compile(r"\<span style='font-size: x-small;'\>.*?\</span\>")
new_text = pattern.sub(lambda match: match.group(0).replace(match.group(0),'') ,text)
我宁愿使用Python本身,因为我对regex一无所知(如你所见……)。但是,如果使用正则表达式,我会选择它。
发布于 2018-06-27 19:15:49
您可以使用find、索引和字符串连接。
new_text = text[:text.find("<span")]+text[text.find("</span>")+7:]
text.find("</span>")+7
查找第一次出现的索引,然后在该索引上加上7,即标签本身的长度。
有很多方法可以解决这个问题。对于任何重要的html解析,我推荐使用Beautifulsoup。
发布于 2018-06-28 05:32:34
我找到了美汤的一种方法:
from bs4 import BeautifulSoup
soup = BeautifulSoup(text, 'html.parser')
spans_to_delete = soup.find_all('span', style=lambda value: value and 'font-size: x-small' in value)
if spans_to_delete:
for span in spans_to_delete:
span.extract()
new_text = str(soup)
else:
print('No span with desired style found')
实际上,this线程的第一个答案给了我方向。
发布于 2018-06-27 19:33:13
我会选择regex。
正则表达式\<span(.*)span>
匹配span标记内的所有内容,包括开始标记和结束标记。试试这个:
String text = "<p>Bla bla bla.</p><p>Blo blo blo<a
href=\"http://www.example.com\">bli bli</a>.</p><p>blu blu<br><span
style=\"font-size: x-small;\"><br>content to remove</span></p>";
text = text.replaceAll("\\<span(.*)span>", "");
https://stackoverflow.com/questions/51061219
复制相似问题