J'ai un texte wiki commeComment puis-je laisser des espaces blancs dans nestedExpr pyparsing
data = """
{{hello}}
{{hello world}}
{{hello much { }}
{{a {{b}}}}
{{a
td {
}
{{inner}}
}}
« » »
et je veux extraire les macros à l'intérieur macro est un texte compris entre {{
et }}
donc j'essayé d'utiliser nestedExpr
from pyparsing import *
import pprint
def getMacroCandidates(txt):
candidates = []
def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString.copy()):
if opener == closer:
raise ValueError("opening and closing strings cannot be the same")
if content is None:
if isinstance(opener,str) and isinstance(closer,str):
if ignoreExpr is not None:
content = (Combine(OneOrMore(~ignoreExpr +
~Literal(opener) + ~Literal(closer) +
CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1))
).setParseAction(lambda t:t[0]))
ret = Forward()
ret <<= Group(opener + ZeroOrMore(ignoreExpr | ret | content) + closer)
ret.setName('nested %s%s expression' % (opener,closer))
return ret
# use {}'s for nested lists
macro = nestedExpr("{{", "}}")
# print(((nestedItems+stringEnd).parseString(data).asList()))
for toks, preloc, nextloc in macro.scanString(data):
print(toks)
return candidates
data = """
{{hello}}
{{hello world}}
{{hello much { }}
{{a {{b}}}}
{{a
td {
}
{{inner}}
}}
"""
getMacroCandidates(data)
Ce qui me donne les jetons et espaces enlevé
[['{{', 'hello', '}}']]
[['{{', 'hello', 'world', '}}']]
[['{{', 'hello', 'much', '{', '}}']]
[['{{', 'a', ['{{', 'b', '}}'], '}}']]
[['{{', 'a', 'td', '{', '}', ['{{', 'inner', '}}'], '}}']]
Nous vous remercions à l'avance
Pour obtenir le texte original pour une expression analysable, vous pouvez utiliser l'assistant 'de originalTextFor':' macro = originalTextFor (nestedExpr ("{{", "}}")) '. Cela préservera tous les espaces, les nouvelles lignes, etc. – PaulMcG