[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
def external(conjunct):
return ', '.join(' '.join(clause) for clause in conjunct)

to produce the desired nested lists and string by combining two steps into one. This
form might run faster; we’ll leave it to the reader to decide whether it is more difficult
to understand. As usual, we can test components of this module interactively:


>>> import rules
>>> rules.internal('a ?x, b')
[['a', '?x'], ['b']]

>>> rules.internal_rule('rule x if a ?x, b then c, d ?x')
{'then': [['c'], ['d', '?x']], 'rule': 'x', 'if': [['a', '?x'], ['b']]}

>>> r = rules.internal_rule('rule x if a ?x, b then c, d ?x')
>>> rules.external_rule(r)
'rule x if a ?x, b then c, d ?x.'

Parsing by splitting strings around tokens like this takes you only so far. There is no
direct support for recursive nesting of components, and syntax errors are not handled
very gracefully. But for simple language tasks like this, string splitting might be enough,
at least for prototyping or experimental systems. You can always add a more robust
rule parser later or reimplement rules as Python code or classes.


More on the holmes expert system shell


So how are these rules actually used? As mentioned, the rule parser we just met is part
of the Python-coded holmes expert system shell. Holmes is an old system written
around 1993 and before Python 1.0. It implemented both forward and backward
chaining inference over rule sets. For example, the rule:


rule pylike if ?X likes coding, ?X likes spam then ?X likes Python

can be used both to prove whether someone likes Python (chaining backward, from
“then” to “if”), and to deduce that someone likes Python from a set of known facts
(chaining forward, from “if” to “then”). Deductions may span multiple rules, multiple
clauses represent conjunctions, and rules that name the same conclusion represent
alternatives. holmes also performs simple pattern-matching along the way to assign the
variables that appear in rules (e.g., ?X), and it is able to explain both its deductions and
questions.


Holmes also served as proof of concept for Python in general at a time when such
evidence was still sometimes necessary, and at last check it still worked unchanged on
Python 2.X platforms. However, its code no longer reflects modern Python best prac-
tice. Because of this, I no longer maintain this system today. In fact, it has suffered from
bit rot so much and for so long that I’ve opted not to revisit it for this edition at all. Its
original Python 0.X code is included in the book examples package, but it has not been
ported to Python 3.X form, and does not accurately reflect Python as it exists today.


That is, holmes is an ex-system. It has ceased to be. And it won’t be discussed further
here. For more modern AI tools and support for Python, search the Web. This is a fun


1414 | Chapter 19: Text and Language

Free download pdf