首页 > 解决方案 > Clips Beginner:在 python 和 clipspy 的 clips 规则中添加常规 exp 或任何替代选择 *

问题描述

我有一个与模板事实中给出的路径匹配的剪辑规则,如果路径匹配,则将与该路径关联的 id 和文本断言到另一个模板中。路径只是字典中的文本条目。路径为“//Document/Sect[2]/P[2]”。我想制定一个这样的规则:

Pfad "//Document/Sect[*]/P[*]"

这样它就可以匹配 //Document/Sect[any number here]/P[any number here]。我找不到与此相关的任何内容,所以如果这是可能的,还是有其他选择?任何帮助,将不胜感激。谢谢!以下是我的规则代码:

rule3= """ 
        (defrule createpara
        (ROW (counter ?A) 
             (ID ?id)                  
             (Text ?text)
             (Path "//Document/Sect/P"))
        
        =>
        (assert (WordPR (counter ?A) 
                        (structure ?id) 
                        (tag "PAR") 
                        (style "Paragraph") 
                        (text ?text))))
        """

标签: pythonpython-3.xclipsclipspy

解决方案


CLIPS不支持正则表达式,但您可以通过define_function方法自己添加对它们的支持。

import re
import clips


RULE = """
(defrule example-regex-test
  ; An example rule using the Python function within a test
  (path ?path)
  ; You need to double escape (\\\\) special characters such as []
  (test (regex-match "//Document/Sect\\\\[[0-9]\\\\]/P\\\\[[0-9]\\\\]" ?path))
  =>
  (printout t "Path " ?path " matches the regular expression." crlf))
"""


def regex_match(pattern: str, string: str) -> bool:
    """Match pattern against string returning a boolean True/False."""
    match = re.match(pattern, string)

    return match is not None


env = clips.Environment()
env.define_function(regex_match, name='regex-match')
env.build(RULE)

env.assert_string('(path "//Document/Sect[2]/P[2]")')

env.run()
$ python3 test.py 
Path //Document/Sect[2]/P[2] matches the regular expression.

推荐阅读