使用pyparsing的Markdown语法,获取空格

2024-05-15 00:32:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个小的转换程序,将降价语法转换为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))

我得到的是:

^{pr2}$

我想要的:

The <strong>cat</strong> in the <strong>hat</strong>.

是的,这可以在不使用pyparsing的情况下实现,并且存在其他实用程序来执行完全相同的操作(例如pandoc),但是我想知道如何使用pyparsing来实现这一点。在


Tags: thetextin程序hathtml语法pyparsing
1条回答
网友
1楼 · 发布于 2024-05-15 00:32:48

不是很在行,但是我会尝试使用transformString()而不是{},和{}来匹配标记,比如:

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)

它产生:

^{pr2}$

更新:由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)

相关问题 更多 >

    热门问题