系列文章目录
- python使用textX构建属于自己的语言模型
- python使用textx-model包
前言
textX是一种元语言,用于在Python中构建领域特定语言(DSL)。它的灵感来自Xtext。
简而言之,textX将帮助您以一种简单的方式构建文本语言。您可以发明自己的语言,或者对现有的文本语言或文件格式建立支持。
textX将从单一语言描述(语法)为该语言构建一个解析器和一个元模型(也称为抽象语法)。有关详细信息,请参阅文档。
textX遵循Xtext的语法和语义,但在某些地方有所不同,并使用Arpeggio-PEG解析器在Python中100%实现——没有语法歧义、无限制的前瞻性、解释器风格。
python使用textX构建属于自己的语言模型的文章地址:https://blog.csdn.net/weixin_44836662/article/details/124811515
一、textx-model是什么?
textx-model是以textX为基础构建出可运行条件规则语句然后输出结果的模型
条件规则语句(例):
"(current_medical_program = '白细胞计数') and (specimen_type = '全血') and (medicine_projects in '[1,2,3]') and (time < 6)"
当里面变量是:
"current_medical_program = '白细胞计数';specimen_type = '全血';medicine_projects = '2';time = 5;"
结果输出: True
当里面变量是:
"current_medical_program = '白细胞计数';specimen_type = '全血';medicine_projects = '2';time = 8;"
结果输出: False
二、功能介绍
包含两个模型:通用模型(general_model)和 case when 专用模型(cs_model),它们处理的条件规则语句不同。
包含一个工具:字典转字符串工具(dict_to_str)
-
通用模型
能处理的条件规则语句(例):"(current_medical_program = '白细胞计数') and (specimen_type = '全血') and " "(medicine_projects in '[1,2,3]') and (time < 6)" 使用通用模型: from textx_model import general_model
-
case when 专用模型
能处理的条件规则语句(例):"case when (current_medical_program = '白细胞计数') and (specimen_type = '全血') and " "(medicine_projects in '[1,2,3]') and (time < 6) then '提醒消息:白细胞计数的消息' else ''" 使用case when 专用模型 from textx_model import cs_model
-
字典转字符串工具
from textx_tools import dict_to_str
三、安装
pip install textx-model
四、使用说明
1.通用模型
代码如下(示例):
from textx_model import general_model
rule = "(current_medical_program = '白细胞计数') and (specimen_type = '全血') and " \
"(medicine_projects in '[1,2,3]') and (time < 6)"
true_example = "current_medical_program = '白细胞计数';specimen_type = '全血';medicine_projects = '2';time = 5;"
false_example = "current_medical_program = '白细胞计数';specimen_type = '全血';medicine_projects = '2';time = 8;"
gm = general_model(true_example, rule)
print(gm.run()) # 预期结果:True
gm = general_model(false_example, rule)
print(gm.run()) # 预期结果:False
2.case when 专用模型
代码如下(示例):
from textx_model import cs_model
rule = "case when (current_medical_program = '白细胞计数') and (specimen_type = '全血') and " \
"(medicine_projects in '[1,2,3]') and (time < 6) then '提醒消息:白细胞计数的消息' else ''"
true_example = "current_medical_program = '白细胞计数';specimen_type = '全血';medicine_projects = '2';time = 5;"
false_example = "current_medical_program = '白细胞计数';specimen_type = '全血';medicine_projects = '2';time = 8;"
cs = cs_model(true_example, rule)
print(cs.run()) # 预期结果:提醒消息:白细胞计数的消息
cs = cs_model(false_example, rule)
print(cs.run()) # 预期结果:''
3.字典转字符串工具
代码如下(示例):
from textx_tools import dict_to_str
data_dict = {
'current_medical_program': '白细胞计数',
'specimen_type': '全血',
'medicine_projects': '2',
'time': 8,
'_list': [1, 2, 3]
}
"""
预期结果:
"current_medical_program = '白细胞计数';specimen_type = '全血';medicine_projects = '2';time = 8;_list = '[1,2,3]';"
"""
print(dict_to_str(data_dict))