nltk, reflections

This commit is contained in:
Olga Kwoczak 2023-03-16 15:59:40 +01:00
parent efdc8a0cf2
commit 6ef21ab6ec

View File

@ -1,8 +1,25 @@
from nltk.chat.util import Chat, reflections
import random
import re
# a table of response pairs, where each pair consists of a
# regular expression, and a list of possible responses,
# with group-macros labelled as %1, %2.
reflections = {
"ja jestem": "ty jesteś",
"ja byłem": "ty byłeś",
"ja byłam": "ty byłaś",
"ja": "ty",
"ja będę": "ty będziesz",
"mój": "twój",
"moja": "twoja",
"mi": "ci",
"mnie": "tobie",
"ty jesteś": "ja jestem",
"ty byłeś": "ja byłem",
"ty byłaś": "ja byłam",
"ty": "ja",
"ty będziesz": "ja będę",
"twój": "mój",
"twoja": "moja"
}
pairs = (
(
@ -328,9 +345,6 @@ pairs = (
),
)
eliza_chatbot = Chat(pairs, reflections)
def eliza_chat():
print("Psychoterapueta\n---------")
print("Rozmawiaj z programem, używając języka polskiego, korzystaj z małych i wielkich liter, a także interpunkcji.\n Wpisz \"koniec\", aby zakończyć.")
@ -341,10 +355,68 @@ def eliza_chat():
def demo():
eliza_chat()
class Chat:
def __init__(self, pairs, reflections={}):
self._pairs = [(re.compile(x, re.IGNORECASE), y) for (x, y) in pairs]
self._reflections = reflections
self._regex = self._compile_reflections()
def _compile_reflections(self):
sorted_refl = sorted(self._reflections, key=len, reverse=True)
return re.compile(
r"\b({})\b".format("|".join(map(re.escape, sorted_refl))), re.IGNORECASE
)
def _substitute(self, str):
return self._regex.sub(
lambda mo: self._reflections[mo.string[mo.start(): mo.end()]], str.lower()
)
def _wildcards(self, response, match):
pos = response.find("%")
while pos >= 0:
num = int(response[pos + 1: pos + 2])
response = (
response[:pos]
+ self._substitute(match.group(num))
+ response[pos + 2:]
)
pos = response.find("%")
return response
def respond(self, str):
# check each pattern
for (pattern, response) in self._pairs:
match = pattern.match(str)
# did the pattern match?
if match:
resp = random.choice(response) # pick a random response
resp = self._wildcards(resp, match) # process wildcards
# fix munged punctuation at the end
if resp[-2:] == "?.":
resp = resp[:-2] + "."
if resp[-2:] == "??":
resp = resp[:-2] + "?"
return resp
# Hold a conversation with a chatbot
def converse(self, quit="koniec"):
user_input = ""
while user_input != "koniec":
user_input = "koniec"
try:
user_input = input(">")
except EOFError:
print(user_input)
if user_input:
while user_input[-1] in "!.":
user_input = user_input[:-1]
print(self.respond(user_input))
if __name__ == "__main__":
demo()
eliza_chatbot = Chat(pairs, reflections)
eliza_chat()