我正在尝试学习 Racket,并在此过程中尝试重写 Python 过滤器。我的代码中有以下一对函数:
def dlv(text):
"""
Returns True if the given text corresponds to the output of DLV
and False otherwise.
"""
return text.startswith("DLV") or \
text.startswith("{") or \
text.startswith("Best model")
def answer_sets(text):
"""
Returns a list comprised of all of the answer sets in the given text.
"""
if dlv(text):
# In the case where we are processing the output of DLV, each
# answer set is a comma-delimited sequence of literals enclosed
# in {}
regex = re.compile(r'\{(.*?)\}', re.MULTILINE)
else:
# Otherwise we assume that the answer sets were generated by
# one of the Potassco solvers. In this case, each answer set
# is presented as a comma-delimited sequence of literals,
# terminated by a period, and prefixed by a string of the form
# "Answer: #" where "#" denotes the number of the answer set.
regex = re.compile(r'Answer: \d+\n(.*)', re.MULTILINE)
return regex.findall(text)
据我所知,Racket 中第一个函数的实现大致如下:
(define (dlv-input? text)
(regexp-match? #rx"^DLV|^{|^Best model" text))
这似乎工作正常。在实现第二个功能时,我目前提出了以下(开始):
(define (answer-sets text)
(cond
[(dlv-input? text) (regexp-match* #rx"{(.*?)}" text)]))
这是不正确的,因为regexp-match*
给出了与正则表达式匹配的字符串列表,包括花括号。有谁知道如何获得与 Python 实现相同的行为?此外,任何关于如何使正则表达式“更好”的建议都将不胜感激。