首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Python迁移到Racket (正则表达式库和"Racket方式“)

从Python迁移到Racket (正则表达式库和"Racket方式“)
EN

Stack Overflow用户
提问于 2012-11-29 02:04:55
回答 1查看 499关注 0票数 7

我正在尝试学习球拍,并在此过程中尝试重写一个Python过滤器。我的代码中有以下两个函数:

代码语言:javascript
复制
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中第一个函数的实现如下所示:

代码语言:javascript
复制
(define (dlv-input? text)
    (regexp-match? #rx"^DLV|^{|^Best model" text))

它看起来工作正常。在第二个函数的实现上,我目前提出了以下建议(首先):

代码语言:javascript
复制
(define (answer-sets text)
    (cond
        [(dlv-input? text) (regexp-match* #rx"{(.*?)}" text)]))

这是不正确的,因为regexp-match*给出了一个匹配正则表达式的字符串列表,包括花括号。有人知道如何在Python实现中获得相同的行为吗?此外,任何关于如何使正则表达式“更好”的建议都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-29 02:12:03

你已经很接近了。您只需在regexp-match调用中添加#:match-select cadr

代码语言:javascript
复制
(regexp-match* #rx"{(.*?)}" text #:match-select cadr)

默认情况下,#:match-select的值为car,它返回整个匹配的字符串。cadr选择第一组,caddr选择第二组,依此类推。有关更多详细信息,请参阅regexp-match* documentation

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13611591

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档