Clips 初学者:在 python 和 clipspy 中的 clips 规则中添加常规 exp 或 select * 的任何替代项

Clips Beginner: Add regular exp or any alternative to select * in clips rule in python and clipspy

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

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

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

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))))
        """

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.