使用统一和正则表达式创建关系
Creating relations with unify and regular expression
我正在尝试使用 unify 创建关系,例如:
Boy(Mike) --> Mike is a boy
Girl(Lisa) --> Lisa is a girl
isSister(Mike,Lisa) --> Lisa is Mike's sister
这是我的代码:
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) 时,returns Mike。
这是我得到的:
Traceback (most recent call last): File "main.py", line 17, in
name = match.captures(1)[0] AttributeError: 'NoneType' object has no attribute 'captures'
match
returns None
如果没有匹配项,这似乎发生在 while
循环中的某处。您需要通过以下方式以某种方式处理这种情况:
if match == None:
# handle
或:
try:
name=match.captures(1)[0]
except AttributeError as e:
# handle
您可以选择适合您的解决方案的处理方式,但这是我通常选择的两种模式。我敢肯定还有其他人,但我建议从这里开始。
我正在尝试使用 unify 创建关系,例如:
Boy(Mike) --> Mike is a boy
Girl(Lisa) --> Lisa is a girl
isSister(Mike,Lisa) --> Lisa is Mike's sister
这是我的代码:
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) 时,returns Mike。 这是我得到的:
Traceback (most recent call last): File "main.py", line 17, in name = match.captures(1)[0] AttributeError: 'NoneType' object has no attribute 'captures'
match
returns None
如果没有匹配项,这似乎发生在 while
循环中的某处。您需要通过以下方式以某种方式处理这种情况:
if match == None:
# handle
或:
try:
name=match.captures(1)[0]
except AttributeError as e:
# handle
您可以选择适合您的解决方案的处理方式,但这是我通常选择的两种模式。我敢肯定还有其他人,但我建议从这里开始。