根据已有信息推理未知信息
下面的代码实现的功能是:
根据 harry.py 在Knowledge 提供的信息, 构建一个库, 然后 你给出询问的信息,
它会将根据库中信息, 进行命题的逻辑推理, 最后得到询问信息的 真假情况
由于本人的Python刚学几天, 一些代码实现细节并不是很清楚, 希望大佬看的时候可以的话 提一下意见 (逃
调用方式
创建两个文件, 然后命名为一下名称, 然后在 harry.py 点击运行就好啦~
harry.py
from logic import *
# Create new classes, each having a name, or a symbol, representing each proposition.
rain = Symbol("rain") # It is raining.
hagrid = Symbol("hagrid") # Harry visited Hagrid
dumbledore = Symbol("dumbledore") # Harry visited Dumbledore
# Save sentences into the KB
knowledge = And( # Starting from the "And" logical connective, becasue each proposition represents knowledge that we know to be true.
# 不下雨就去拜访 Hagrid
Implication(Not(rain), hagrid), # ¬(It is raining) → (Harry visited Hagrid)
# 或者 两个都有可能被拜访: 两者的并集
Or(hagrid, dumbledore), # (Harry visited Hagrid) ∨ (Harry visited Dumbledore).
# 不可能两个都去拜访: 两者的交集
Not(And(hagrid, dumbledore)), # ¬(Harry visited Hagrid ∧ Harry visited Dumbledore) i.e. Harry did not visit both Hagrid and Dumbledore.
# 哈利去找邓布利多
dumbledore # Harry visited Dumbledore. Note that while previous propositions contained multiple symbols with connectors, this is a proposition consisting of one symbol. This means that we take as a fact that, in this KB, Harry visited Dumbledore.
)
print(model_check(knowledge, rain)) # 根据构建出来的知识工程来判断 "rain" 状态的真假:也就是通过上面的情况来推断下雨的真假(所以这里是可以换成其他滴~)
logic.py
import itertools
class Sentence():
def evaluate(self, model):
"""Evaluates the logical sentence."""
raise Exception("nothing to evaluate")
def formula(self):
"""Returns string formula representing logical sentence."""
return ""
def symbols(self):
"""Returns a set of all symbols in the logical sentence."""
return set()
@classmethod
def validate(cls, sentence):
if not isinstance(sentence, Sentence): # 判断两个句子是不是相同的类型
raise TypeError("must be a logical sentence")
@classmethod
def parenthesize(cls, s):
"""Parenthesizes an expression if not already parenthesized."""
def balanced(s):
"""Checks if a string has balanced parentheses."""
count = 0
for c in s:
if c == "(":
count += 1
elif c == ")":
if count <= 0:
return False
count -= 1
return count == 0
if not len(s) or s.isalpha() or (
s[0] == "(" and s[-1] == ")" and balanced(s[1: -1])
):
return s
else:
return f"({
s})"
class Symbol(Sentence):
def __init__(self, name)