【问题标题】:Clips Beginner: Add regular exp or any alternative to select * in clips rule in python and clipspyClips Beginner:在 python 和 clipspy 的 clips 规则中添加常规 exp 或任何替代选择 *
【发布时间】:2021-10-25 09:14:52
【问题描述】:

我有一个与模板事实中给出的路径匹配的剪辑规则,如果路径匹配,则将与该路径关联的 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))))
        """

【问题讨论】:

    标签: python python-3.x clips clipspy


    【解决方案1】:

    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.
    

    【讨论】:

      猜你喜欢
      • 2021-02-26
      • 2017-04-05
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多