Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-删除过多的html标记_Python_Html - Fatal编程技术网

Python-删除过多的html标记

Python-删除过多的html标记,python,html,Python,Html,所以我现在有一篇文章: <i>This article is written </i><a href="http://google.com"><i>TEST</i></a><i>.</i> 这篇文章是这样写的。 我认为这是一个很好的HTML,但是,我想清理它,删除所有多余的标记,并将其简化为单个标记: <i>This article is written <a href="htt

所以我现在有一篇文章:

<i>This article is written </i><a href="http://google.com"><i>TEST</i></a><i>.</i>
这篇文章是这样写的。
我认为这是一个很好的HTML,但是,我想清理它,删除所有多余的
标记,并将其简化为单个
标记:

<i>This article is written <a href="http://google.com">TEST</a>.</i>
这篇文章是这样写的。
我试图自己把它清理干净,但我需要向前看文本,在这方面没有太大的成功。是否有我可以使用的软件包,或者我可以使用的方法,或者我必须手动操作


谢谢

使用HTML解析器绝对是最可靠的解决方案。它将能够处理跨多行分割的标签

下面将解决您的示例,但可能不会更多

def OuterI(text):
    outer = re.search("(.*?)(\<i\>.*<\/i\>)(.*)", text)

    if outer:
        return "%s<i>%s</i>%s" % (outer.group(1), re.sub(r"(\<\/?[iI]\>)", "", outer.group(2)), outer.group(3))
    else:
        return text

print OuterI('<i>This article is written </i><a href="http://google.com"><i>TEST</i></a><i>.</i>')
print OuterI('text before <i>This article is written </i><a href="http://google.com"><i>TEST</i></a><i>.</i> text after')
def OuterI(文本):
外部=重新搜索((.*)(\.*)(.*),文本)
如果是外部的:
返回“%s%s%s”%(外部组(1)、re.sub(r“(\)”、“”、外部组(2))、外部组(3))
其他:
返回文本
打印OuterI('这篇文章是写的')
print OuterI('写这篇文章之前的文本,后面的文本')

我不知道有什么能做到这一点。这两个HTML片断不等价(例如,如果有CSS规则<代码> I A/CODE >,它将匹配第二个,但不是第一个),所以您必须精确地解释您认为哪些重要的语义变化,哪些不是重要的。