我正在尝试学习球拍,并在此过程中尝试重写一个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)据我所知,function中第一个函数的实现如下所示:
(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实现中获得相同的行为吗?此外,任何关于如何使正则表达式“更好”的建议都将不胜感激。
发布于 2012-11-29 02:12:03
你已经很接近了。您只需在regexp-match调用中添加#:match-select cadr:
(regexp-match* #rx"{(.*?)}" text #:match-select cadr)默认情况下,#:match-select的值为car,它返回整个匹配的字符串。cadr选择第一组,caddr选择第二组,依此类推。有关更多详细信息,请参阅regexp-match* documentation。
https://stackoverflow.com/questions/13611591
复制相似问题