【问题标题】:Creating relations with unify and regular expression使用统一和正则表达式创建关系
【发布时间】:2018-11-18 14:27:43
【问题描述】:

我正在尝试创建与统一的关系,例如:

Boy(Mike) --> Mike 是个男孩

Girl(Lisa) --> Lisa 是个女孩

isSister(Mike,Lisa) --> Lisa 是 Mike 的妹妹

这是我的代码:

from fact import Fact
from logic import get, unify, var

from itertools import chain 
import regex as re


facts = {}

pattern = r"(\w+)\((?:([^,\)]+)\,(?:([^,\)]+)))+\)\.?"

rule = input('Ingrese un hecho o consulta:')
while rule != '!':
  match = re.match(pattern, rule)
  print(match)
  name = match.captures(1)[0]
  argument1 = match.captures(2)
  argument2 = match.captures(3)
  if rule.endswith('.'):
    if not name in facts:
      facts[name] = Fact()
    facts[name].append(argument1[0])
    facts[name].append(argument2[0])
  else:
    X = var()
    Y = var()
    for _ in facts[name](X,Y): print(get(X),get(Y))
  rule = input('Ingrese un hecho o consulta:')

我想要的是,当我请求 isSister(?,Lisa) 时,它会返回 Mike。 这是我得到的:

Traceback(最近一次调用最后一次):文件“main.py”,第 17 行,在 name = match.captures(1)[0] AttributeError: 'NoneType' object has no attribute 'captures'

【问题讨论】:

    标签: python regex dictionary logic-programming unify


    【解决方案1】:

    match 如果没有匹配则返回None,这似乎发生在while 循环中的某处。您需要通过以下方式处理这种情况:

    if match == None:
        # handle
    

    或:

    try:
       name=match.captures(1)[0]
    except AttributeError as e:
        # handle
    

    您可以选择适合您的解决方案的处理方式,但这是我通常采用的两种模式。我确定还有其他人,但我建议从这里开始。

    【讨论】:

    • 它不应该返回 None,因为它会收到我发送的内容,例如,如果我发送 IsSister(Mike, Lisa),name = IsSister。当我尝试像 IsSister(?, Lisa) 一样调用它时,这只返回错误
    • 它应该返回None,文档特别告诉你自己处理None的情况:“由于match()和search()在没有匹配的时候返回None,你可以测试是否有匹配用一个简单的 if 语句”
    猜你喜欢
    • 1970-01-01
    • 2010-10-29
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    相关资源
    最近更新 更多