基于层次匹配的规则引擎

问题描述 投票:0回答:1

说,我有一个具有这种结构的数据集(城市):

  • ID
  • 城市
  • 状态
  • 国家
  • 大陆

而且我有一个配置表(键,值),其中键可以是上述参数的组合

例如:

{
    "continent": "asia"
}

{
    "continent": "asia",
    "country" : "india"
}

{
    "continent": "asia",
    "country" : "india",
    "state" : "maharashtra",
    "city" : "mumbai"
}

现在,我想从第一个数据集到配置中的条目进行最接近的城市匹配。

例如,如果我有

city: mumbai, state: maharashtra, country: india, continent: asia

它应该匹配,上面配置中的第三个条目。

如果有

city: tokyo, state: Kantō, country: japan, continent: asia

它应该与上面配置中的第一个条目匹配。

如果这种情况下有现成的东西,我正在寻找建议。

如果有的话,我愿意以不同的方式存储配置。

理想情况下,我希望我可以传递multiple条目,并且它应该返回最接近的匹配配置。

python algorithm matching rule-engine
1个回答
0
投票

OrderedDict在这里会很有用,因此您可以保留城市>州>国家>洲的层次结构。

from collections import OrderedDict

config = OrderedDict({"city" : "mumbai",
                      "state" : "maharashtra",
                      "country" : "india",
                      "continent": "asia"})

def get_closest_match(**kwargs):
    for key in config.keys():
        if kwargs[key] == config[key]:
            return f'{key}: {config[key]}'


>>> get_closest_match(city='mumbai', state='maharashtra', country='india', continent='asia')
'city: mumbai'
>>> get_closest_match(city='tokyo', state='Kantō', country='japan', continent='asia')
'continent: asia'
© www.soinside.com 2019 - 2024. All rights reserved.