【问题标题】:Replace some HTML tags with special characters with Python [closed]用 Python 替换一些带有特殊字符的 HTML 标签 [关闭]
【发布时间】:2021-07-06 19:42:33
【问题描述】:

我有一些字符串包含一些 HTML 标签,如 <strong><em><br/>,我需要分别用 *_\n 替换这些标签;

例如:

"this string contain <strong>bold</strong> and <em>italic</em> formatted text.<br/>How can I substitute these <strong><em>HTML tags</em></strong> with <strong>Python</strong>?"

必须成为

"this string contain *bold* and _italic_ formatted text.\nHow can I substitute these *_HTML tags_* with *Python*?".

执行此操作的最佳做​​法是什么?也许正则表达式?怎么样?

【问题讨论】:

    标签: python html regex string replace


    【解决方案1】:

    最好的做法是什么?也许是正则表达式?

    当然不是,当您需要使用 Chomsky Type-2 时,正则表达式非常适合处理 Chomsky Type-3。

    您可以按照以下方式使用html.parser 内置模块

    from html.parser import HTMLParser
    changes = {"strong": "*", "em": "_", "br": "\n"}
    class Converter(HTMLParser):
        def __init__(self, *args, **kwargs):
            self.out = ""
            super().__init__(*args, **kwargs)
        def handle_starttag(self, tag, attrs):
            self.out += changes.get(tag, tag)
        def handle_endtag(self, tag):
            if tag != "br":
                self.out += changes.get(tag, tag)
        def handle_data(self, data):
            self.out += data
    
    txt = "this string contain <strong>bold</strong> and <em>italic</em> formatted text.<br/>How can I substitute these <strong><em>HTML tags</em></strong> with <strong>Python</strong>?"
    
    conv = Converter()
    conv.feed(txt)
    print(conv.out)
    

    输出

    this string contain *bold* and _italic_ formatted text.
    How can I substitute these *_HTML tags_* with *Python*?
    

    请注意,我会忽略 br 结束标签,否则 &lt;br/&gt; 会导致双换行符。

    【讨论】:

    • 谢谢,我不知道 html.parser 模块。我还必须导入 abc 并将 ABC 作为 Converter 的基类。
    【解决方案2】:

    不要 python,但是用*替换&lt;/?strong&gt;和用_替换&lt;/?em&gt;应该这样做。

    &lt;/?strong&gt; 匹配&lt;strong&gt; &lt;/strong&gt;,因为/? 设为可选。

    Example for strong here on regex101.

    【讨论】:

    • 谢谢,这个解决方案有效,但我认为@Daweo 解决方案更“Pythonic”。
    猜你喜欢
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多