2a3e04cf810185ae9e5c6cd34ae107a37cd98b0a
7 Match
= collections
.namedtuple('Match', 'text, rule, bindings')
17 def read_rules(rules_file
):
18 with
open(rules_file
) as f
:
19 rules
= [{'pattern': r
['pattern'].split(),
20 'responses': [t
.split() for t
in r
['responses']]}
21 for r
in yaml
.load(f
)]
29 return [(item
[:i
], item
[i
:]) for i
in range(len(item
)+1)]
31 def match(text
, rule
):
32 return all_matches([Match(text
, rule
, {})])
34 def all_matches(matches
):
37 # print(matches, successes)
40 if successful_match(current
):
41 successes
+= [current
.bindings
]
43 new_matches
= match_item(current
.text
, current
.rule
, current
.bindings
)
44 matches
= matches
[1:] + new_matches
47 def successful_match(match
):
48 return match
.text
== [] and match
.rule
== []
50 def match_item(text
, rule
, bindings
):
54 # already seen this variable
55 if text
[:len(bindings
[r0
])] == bindings
[r0
]:
56 return [Match(text
[(len(bindings
[r0
])):], rule
[1:], bindings
)]
60 # not seen this variable yet
62 for pre
, suf
in splits(text
):
63 new_bindings
= bindings
.copy()
64 new_bindings
[r0
] = pre
65 matches
+= [Match(suf
, rule
[1:], new_bindings
)]
67 elif text
and text
[0] == r0
:
68 return [Match(text
[1:], rule
[1:], bindings
)]
72 def candidate_rules(rules
, comment
):
73 return [(rule
, bindings
)
75 for bindings
in match(comment
, rule
['pattern'])]
78 def fill(response
, bindings
):
83 filled_response
+= bindings
[w
]
85 filled_response
+= ['MISSING']
87 filled_response
+= [w
]
88 return filled_response
91 def pronoun_person_swap(bindings
):
95 if w
in pronoun_swaps
:
96 sw
+= [pronoun_swaps
[w
]]
101 return {var
: swapped(bindings
[var
]) for var
in bindings
}
103 def respond(rule
, bindings
):
104 return fill(random
.choice(rule
['responses']), bindings
)
107 def eliza_loop(rules
):
108 print("Hello. I'm Eliza. What seems to be the problem?")
111 if c
.strip() in 'quit halt exit stop'.split(): break
113 rule
, bindings
= candidate_rules(rules
, comment
)[0]
114 swapped_bindings
= pronoun_person_swap(bindings
)
115 print(' '.join(respond(rule
, swapped_bindings
)))
118 all_rules
= read_rules('rules.yaml')
119 eliza_loop(all_rules
)