gpt4 book ai didi

python - 如何替换字符串中的成对标记?

转载 作者:太空狗 更新时间:2023-10-29 23:56:01 28 4
gpt4 key购买 nike

python 的新手,精通几种语言,但看不到执行以下操作的“时髦”方法。我敢肯定它正在为正则表达式尖叫,但我能想出的任何解决方案(使用正则表达式组等等)很快就会变得疯狂。

因此,我有一个带有类似 html 标签的字符串,我想将其替换为实际的 html 标签。

例如:

Hello, my name is /bJane/b.

应该变成:

Hello, my name is <b>Jane</b>.

它也可以与 [i]talic 和 [u]nderline 组合使用:

/iHello/i, my /uname/u is /b/i/uJane/b/i/u.

应该变成:

<i>Hello</i>, my <u>name</u> is <b><i><u>Jane</b></i></u>.

显然,直接的 str.replace 是行不通的,因为每个第二个标记都需要以正斜杠开头。

为了清楚起见,如果 token 被组合,它总是先打开,先关闭。

非常感谢!

PS:在任何人兴奋之前,我知道这种事情应该用 CSS 来完成,废话,废话,废话,但我没有编写软件,我只是在逆向它的输出!

最佳答案

也许这样的事情可以帮助:

import re


def text2html(text):
""" Convert a text in a certain format to html.

Examples:
>>> text2html('Hello, my name is /bJane/b')
'Hello, my name is <b>Jane</b>'
>>> text2html('/iHello/i, my /uname/u is /b/i/uJane/u/i/b')
'<i>Hello</i>, my <u>name</u> is <b><i><u>Jane</u></i></b>'

"""

elem = []

def to_tag(match_obj):
match = match_obj.group(0)
if match in elem:
elem.pop(elem.index(match))
return "</{0}>".format(match[1])
else:
elem.append(match)
return "<{0}>".format(match[1])

return re.sub(r'/.', to_tag, text)

if __name__ == "__main__":
import doctest
doctest.testmod()

关于python - 如何替换字符串中的成对标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5331514/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com