我正在编写一个小型转换程序,该程序将Markdown语法简化为html(作为学习练习),但是我无法正确设置间距:
from pyparsing import *
strong = QuotedString("**")
text = Word(printables)
tokens = strong | text
grammar = OneOrMore(tokens)
strong.setParseAction(lambda x:"<strong>%s</strong>"%x[0])
A = "The **cat** in the **hat**."
print ' '.join(grammar.parseString(A))
我得到的是:
The <strong>cat</strong> in the <strong>hat</strong> .
我想要的是:
The <strong>cat</strong> in the <strong>hat</strong>.
是的,可以在没有pyparsing的情况下完成此操作,并且存在其他实用程序可以做完全相同的事情(例如pandoc),但是我想知道如何使用pyparsing做到这一点。
pyparsing不太熟练,但是我会尝试使用transformString()
代替parseString()
和leaveWhitespace()
来匹配标记,例如:
from pyparsing import *
strong = QuotedString("**").leaveWhitespace()
text = Word(printables).leaveWhitespace()
tokens = strong | text
grammar = OneOrMore(tokens)
strong.setParseAction(lambda x:"<strong>%s</strong>"%x[0])
A = "The **cat** in the **hat**."
print grammar.transformString(A)
它产生:
The <strong>cat</strong> in the <strong>hat</strong>.
更新:Paul McGuire指出的改进版本(请参阅评论):
from pyparsing import *
strong = QuotedString("**")
strong.setParseAction(lambda x:"<strong>%s</strong>"%x[0])
A = "The **cat** in the **hat**."
print strong.transformString(A)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句