【问题标题】:Remove all the Html content from a string in python从python中的字符串中删除所有Html内容
【发布时间】:2018-08-01 22:21:39
【问题描述】:

我想从字符串中删除所有 HTML 内容。

我有一个字符串

str= "I am happy with <body> <h1>This is a Heading</h1>  <p>This is a paragraph.</p> </body> 3333  <body> <h1>This is a Heading</h1>  <p>This is a paragraph.</p> </body> your code"

我想要最后的字符串 str= "I am happy with 3333 your code"

我已经编写了这段代码来完成上述任务。

def removetags(input_str):
    result = ''
    startflag = 0
    start=True
    count=0
    for ch in input_str:
        if ch == '<':
            if count!=len(input_str)-1:
                if input_str[count+1]!='/':
                    start=True
                    startflag += 1


        elif (ch == '>') and startflag :
            if not start:
                startflag -= 1
            start=False

        elif (not startflag) :
            result += ch

        count += 1

    return result

print(removetags(str))

这可以正常工作,但如果您在文本中有&lt;,那么它将无法正确输出。所以我想使用 html 解析来删除。有没有办法做到这一点?我找到了这个库,但我找不到这样做的方法。提前致谢。

【问题讨论】:

    标签: python html parsing jira preprocessor


    【解决方案1】:
    from html.parser import HTMLParser
    
    str = "I am happy with <body> <h1>This is a Heading</h1>  <p>This is a paragraph.</p> </body> 3333 > <body> <h1>This is a Heading</h1>  <p>This is a paragraph.</p> </body> your code"
    
    class MyHTMLParser(HTMLParser):
        got_html_in_tags = False
        html_free_text = []
    
        def handle_starttag(self, tag, attrs):
            self.got_html_in_tags = True
    
        def handle_endtag(self, tag):
            self.got_html_in_tags = False
    
        def handle_data(self, data):
            if not self.got_html_in_tags:
                self.html_free_text.append(data)
    
    
    parser = MyHTMLParser()
    parser.feed(str)
    print("".join(parser.html_free_text))
    

    这将打印I am happy with 3333 your code,即使文本中有“>”或“

    【讨论】:

    • 如何将其作为最终字符串? @坚果
    • 它正在工作,但我想要一个变量的最终字符串 a=parser.feed(str) 不起作用?我认为它没有返回字符串。 @坚果
    • @Sathiyakugan parser.feed(str) 不返回任何内容。如果你想获取 html,你应该调用 parser.html_free_text - 它返回没有标签的行列表
    • 它说 AttributeError: 'MyHTMLParser' object has no attribute 'html_free_text' @Nuts
    • @Sathiyakugan 复制代码示例然后...我更新了代码
    【解决方案2】:

    另一个re解决方案:

    re.sub(r'(<(?P<tag>[a-zA-Z0-9]+)>.*?</(?P=tag)>)', '', string)
    

    测试:

    >>> re.sub(r'(<(?P<tag>[a-zA-Z0-9]+)>.*?</(?P=tag)>)', '', string)
    'I am happy with  3333   your code'
    >>> string = "I am happy with <body> <h1>This is a Heading</h1>  <p>This is a paragraph.</p> </body> 3333 > <body> <h1>This is a Heading</h1>  <p>This is a paragraph.</p> </body> your code"
    >>> re.sub(r'(<(?P<tag>[a-zA-Z0-9]+)>.*?</(?P=tag)>)', '', string)
    'I am happy with  3333 >  your code'
    >>> string = "I am <a happy with <body> </body> lal"
    >>> re.sub(r'(<(?P<tag>[a-zA-Z0-9]+)>.*?</(?P=tag)>)', '', string)
    'I am <a happy with  lal'
    

    【讨论】:

      【解决方案3】:

      您可以为此使用正则表达式库,

      import re
      str= "I am happy with <body> <h1>This is a Heading</h1>  <p>This is a paragraph.</p> </body> 3333  <body> <h1>This is a Heading</h1>  <p>This is a paragraph.</p> </body> your code"
      comp = re.compile(r'<([\w]+)[^>]*>(.*?)<\/\1>')
      data = re.sub(comp, '', str)
      print(data)
      

      可能是这个帮助

      【讨论】:

      • 这给出了字符串“我对你的代码很满意”。这不包括“3333”,因此不应错过该部分。我只想要一个 HTML 解析器的方法来删除它。
      【解决方案4】:

      让我们递归地做这个;)

      基本情况 1:当文本为空字符串时,
      返回一个空字符串

      基本情况 2:当文本的第一个字母是插入符号时,
      搜索结束标记并在结束标记后返回剩余文本的函数调用。

      def remove_tags(text, tags=[]):
        if text == '':
          return text
      
        if text[0] == '<':
          closing_caret_pos = text.find('>')
          tag = text[0:closing_caret_pos+1]
          is_open_tag = '/' not in tag
          is_close_tag = not is_open_tag
          is_valid_tag = tag[1:-1].isalpha() or tag[2:-1].isalpha()
      
          if is_valid_tag and is_open_tag:
            tags.append(tag)
            return remove_tags(text[1:], tags)
          if is_valid_tag and is_close_tag:
            tags.pop()
            return remove_tags(text[len(tag):], tags)
      
        if len(tags) != 0: # when an open tag exists keeping looking
          return remove_tags(text[1:], tags)
      
        return text[0] + remove_tags(text[1:], tags)
      

      测试运行:

      text = "I am happy with <body> <h1>This is a Heading</h1>  <p>This is a paragraph.</p> </body> 3333  <body> <h1>This is a Heading</h1>  <p>This is a paragraph.</p> </body> your code"
      print(remove_tags(text))
      >
      I am happy with  3333   your code
      
      text = "x<=1 <div> cookies </div>"
      print(remove_tags(text))
      >
      x<=1 
      
      text = "I am <a happy with <body> </body> lal"
      print(remove_tags(text))
      >
      I am <a happy with  lal
      

      【讨论】:

      • 不适用于字符串I am &lt;a happy with &lt;body&gt; &lt;/body&gt; lal
      • 不应该。您的示例不是有效的标记。 OP 没有提及非结构化标记,我猜想处理这样的示例可能需要标记解析器
      • 有效。我的html中可能有数学问题x&lt;=1 &lt;div&gt; cookies &lt;/div&gt;
      猜你喜欢
      • 2014-03-21
      • 1970-01-01
      • 2014-03-26
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 2016-02-20
      • 2011-11-08
      相关资源
      最近更新 更多