如何用 python 和聪明的方式涵盖 <strong> <em> <u> 到 <strong> 的所有情况?

How to cover all case of <strong> <em> <u> to <strong> with python and smart way?

如何用python和聪明的方式涵盖<strong> <em> <u><strong>的所有情况?

我正在尝试用代码来解决这个问题,但我认为我的方法并不好,而且有很多案例。

有没有人想知道如何更好地做到这一点?

我很想有两种学习方式:

我现在的代码:

html = '''
<h1>Make bakery</h1>
<p>Step 1: Please use good quality product for make <strong><em>bakery</em></strong></p>
<p>Step 2: Make <em><u>bakery</u></em> hot</p>
<p>Step 2: Make <em><strong><u>bakery</u></strong></em> hot</p>
'''

def function_cover_all_strong(html):

    html = html.replace('<u><em><strong>','<strong>')
    html = html.replace('</strong></em></u>','</strong>')

    html = html.replace('<em><strong><u>','<strong>')
    html = html.replace('</u></strong></em>','</strong>')

    html = html.replace('<strong><u><em>','<strong>')
    html = html.replace('</em></u></strong>','</strong>')

    html = html.replace('<strong><em><u>','<strong>')
    html = html.replace('</u></em></strong>','</strong>')

    html = html.replace('<em><u>','<strong>')
    html = html.replace('</u></em>','</strong>')

    html = html.replace('<u><strong>','<strong>')
    html = html.replace('</strong></u>','</strong>')

    html = html.replace('<u><em>','<strong>')
    html = html.replace('</em></u>','</strong>')

    html = html.replace('<strong><u>','<strong>')
    html = html.replace('</u></strong>','</strong>')

    html = html.replace('<strong><em>','<strong>')
    html = html.replace('</em></strong>','</strong>')

    html = html.replace('<u>','<strong>')
    html = html.replace('</u>','</strong>')

    html = html.replace('<em>','<strong>')
    html = html.replace('</em>','</strong>')

    return html

html_cover = function_cover_all_strong(html = html)
print(html_cover)

感谢您的支持!祝你一切顺利。我很想研究更多但没有看到这样的案例!

使用简单的列表和 for 循环怎么样?

def function_cover_all_strong(html):

    #convert <strong class"some-thing" id="something"> to <strong>
    while '<strong class' in html:
        i = html.find('<strong class') #find start index
        j = html[i:].find('>') #find end index
        html = html[:i] + '<strong>' + html[j:] #replace


    #convert tags
    tags = ['<u><em><strong>', '</strong></em></u>', '<em><strong><u>']
    for old_tag in tags:
        if '/' in tag:
            new_tag = '</strong>'
        else:
            new_tag = '<strong>'

        html = html.replace(old_tag, new_tag)

    return html