python - 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))))
"""
解决方案
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.
推荐阅读
- c# - 是否可以将 Linq.Queryable.Max 作为参数传递?
- vcpkg - 致命错误 C1083:无法打开包含文件:'ifaddrs.h':没有这样的文件或目录
- javascript - 如何在 PartialView 表单上保留 HTTPPost 操作中的数据,以在另一个 PartialView [ASP.NET] 上的 HTTPGet 操作中使用
- spring-boot - 如何在 Thymeleaf 的翻译中使用链接(锚标记)?
- python-3.x - django 自定义用户注册模型中密码重置的默认模板名称
- powershell - 用于下载 .Net Core 5.0.4 Hosting Bundle Installer 的 Powershell 命令
- git - 为什么直接在节点上运行 cmd 时 Jenkins 不能从 Git 获取?
- git - 项目解决方案正在显示 Git 文件
- python - 我无法解决这个问题“IndexError: list index out of range”
- java - 在 Prod env Java 批处理中有时会因未找到类异常而出现 NoClassdeffoundError 失败。一天或一周至少发生一次