gpt4 book ai didi

python - 删除Python中嵌套的bbcode引号?

转载 作者:行者123 更新时间:2023-11-30 23:47:15 25 4
gpt4 key购买 nike

我尝试搜索此内容,但只找到了 PHP 答案。我在 Google App Engine 上使用 Python,并尝试删除嵌套引号。

例如:

[quote user2]
[quote user1]Hello[/quote]
World
[/quote]

我想运行一些东西来获取最外面的报价。

[quote user2]World[/quote]

最佳答案

不确定您是否只需要引号,或者删除嵌套引号的整个输入。这个 pyparsing 示例同时执行以下两个操作:

stuff = """
Other stuff
[quote user2]
[quote user1]Hello[/quote]
World
[/quote]
Other stuff after the stuff
"""

from pyparsing import (Word, printables, originalTextFor, Literal, OneOrMore,
ZeroOrMore, Forward, Suppress)

# prototype username
username = Word(printables, excludeChars=']')

# BBCODE quote tags
openQuote = originalTextFor(Literal("[") + "quote" + username + "]")
closeQuote = Literal("[/quote]")

# use negative lookahead to not include BBCODE quote tags in tbe body of the quote
contentWord = ~(openQuote | closeQuote) + (Word(printables,excludeChars='[') | '[')
content = originalTextFor(OneOrMore(contentWord))

# define recursive definition of quote, suppressing any nested quotes
quotes = Forward()
quotes << ( openQuote + ZeroOrMore( Suppress(quotes) | content ) + closeQuote )

# put separate tokens back together
quotes.setParseAction(lambda t : '\n'.join(t))

# quote extractor
for q in quotes.searchString(stuff):
print q[0]

# nested quote stripper
print quotes.transformString(stuff)

打印:

[quote user2]
World
[/quote]

Other stuff
[quote user2]
World
[/quote]
Other stuff after the stuff

关于python - 删除Python中嵌套的bbcode引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8453828/

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