Python - 带命题的字典(替换字符串值)

Python - dictionary with propositions (replace string values)

我有一些字典,例如形式:

my_dictionary = {'A': '¬(p)', 'B': '→(q, ∧(¬(p), ∨(y, z)))', 'Aim': ['p', '→(p, q)']}

他们是用 (q→(¬(p)∧(y∨z)))(p→q) 替换 →(q, ∧(¬(p), ∨(y, z)))→(p, q) 形式的字典值中出现的所有字符串的简单方法吗?

最简单的方法可能是使用任何可用的 string interpolation methods or regular expressions. Judging from your background in prolog, to handle first-order logic properly, you might want to look into using a FOL parse or full on solving engines, like pyprover, pyPL, PyLog or pythogic

我自己使用一些序言找到了一些解决方案:

序言文件(称为“logic.pl”)必须包含以下代码:

:-op(800, fx, ~).
:-op(801, xfy, ∧).
:-op(802, xfy, ∨).
:-op(803, xfy, →).
:-op(804, xfy, ↔).


m_Proposition_Binary_x_y(X ∨ Y, X, Y).
m_Proposition_Binary_x_y(X ∧ Y, X, Y).
m_Proposition_Binary_x_y(X → Y, X, Y).
m_Proposition_Binary_x_y(X ↔ Y, X, Y).

现在我们可以定义一些函数了:

from pyswip import Prolog

def normalize(collection):
    interface = Prolog()
    interface.consult("Prolog/logic.pl")

    if type(collection) is str:
        proposition = collection
        try:
            rest = list(interface.query(f"m_Proposition_Binary_x_y({proposition},A,B)".replace("'","")))[0]
            return f"({normalize(rest['A'])}{proposition[0]}{normalize(rest['B'])})"
        except:
            return proposition
    
    elif type(collection) is list:
        return [normalize(x) for x in collection]
    elif type(collection) is dict:
        old_dict = collection
        new_dict = {}

        for key in old_dict:
            new_dict[key] = normalize(old_dict[key])

        return new_dict 

有了这个背景,就可以很容易地规范化字典:

my_dictionary = {'A': '~(p)', 'B': '→(q, ∧(~(p), ∨(y, z)))', 'Aim': ['p', '→(p, q)']}

print(m_str.normalize(my_dictionary))

输出:

{'A': '~(p)', 'B': '(q→(~(p)∧(y∨z)))', 'Aim': ['p', '(p→q)']}

唯一的问题,出于某种原因,我不能在 pyswip 库(版本:0.2.11)中使用 ¬ 而不是 ~,因为 ¬ 我得到了 curios 错误:

U+ffffffac is not in range [U+0000; U+10ffff]

由此 ¬ 具有 unicode U+00AC ..