質問編集履歴
1
responderクラスのコード追加
title
CHANGED
File without changes
|
body
CHANGED
@@ -109,7 +109,86 @@
|
|
109
109
|
return self._pattern
|
110
110
|
|
111
111
|
```
|
112
|
+
responder.py
|
113
|
+
```
|
114
|
+
import re
|
112
115
|
|
116
|
+
from random import choice
|
117
|
+
|
118
|
+
class Responder:
|
119
|
+
"""AIの応答を制御する思考エンジンの基底クラス。
|
120
|
+
継承して使わなければならない。
|
121
|
+
|
122
|
+
メソッド:
|
123
|
+
response(str) -- ユーザーの入力strを受け取り、思考結果を返す
|
124
|
+
|
125
|
+
プロパティ:
|
126
|
+
name -- Responderオブジェクトの名前
|
127
|
+
"""
|
128
|
+
|
129
|
+
def __init__(self, name, dictionary):
|
130
|
+
"""文字列を受け取り、自身のnameに設定する。
|
131
|
+
辞書dictionaryを受け取り、自身のdictionaryに保持する。"""
|
132
|
+
self._name = name
|
133
|
+
self._dictionary = dictionary
|
134
|
+
|
135
|
+
def response(self, *args):
|
136
|
+
"""文字列を受け取り、思考した結果を返す。"""
|
137
|
+
pass
|
138
|
+
|
139
|
+
@property
|
140
|
+
def name(self):
|
141
|
+
"""思考エンジンの名前"""
|
142
|
+
return self._name
|
143
|
+
|
144
|
+
class WhatResponder(Responder):
|
145
|
+
"""AIの応答を制御する思考エンジンクラス。
|
146
|
+
入力に対して疑問形で聞き返す。"""
|
147
|
+
|
148
|
+
def response(self, text):
|
149
|
+
"""文字列textを受け取り、'{text}ってなに?'という形式で返す。"""
|
150
|
+
return '{}ってなに?'.format(text)
|
151
|
+
|
152
|
+
class RandomResponder(Responder):
|
153
|
+
"""AIの応答を制御する思考エンジンクラス。
|
154
|
+
登録された文字列からランダムなものを返す。
|
155
|
+
"""
|
156
|
+
|
157
|
+
|
158
|
+
def __init__(self, name):
|
159
|
+
"""文字列を受け取り、オブジェクトの名前に設定する。
|
160
|
+
'dics_random.txt'ファイルから応答文字列のリストを読み込む。"""
|
161
|
+
super().__init__(name)
|
162
|
+
self.responses = []
|
163
|
+
with open('dics_random.txt', mode='r', encoding='utf-8') as f:
|
164
|
+
self._responses = [x for x in f.read().splitlines() if x]
|
165
|
+
|
166
|
+
|
167
|
+
def response(self, _):
|
168
|
+
"""ユーザーからの入力は受け取るが、使用せずにランダムな応答を返す。"""
|
169
|
+
return choice()
|
170
|
+
|
171
|
+
|
172
|
+
@property
|
173
|
+
def name(self):
|
174
|
+
"""思考エンジンの名前"""
|
175
|
+
return self._name
|
176
|
+
|
177
|
+
class PatternResponder(Responder):
|
178
|
+
"""AIの応答を制御する思考エンジンクラス。
|
179
|
+
登録されたパターンに反応し、関連する応答を返す。
|
180
|
+
"""
|
181
|
+
|
182
|
+
def response(self, text):
|
183
|
+
"""ユーザーの入力に合致するパターンがあれば、関連するフレーズを返す。"""
|
184
|
+
for ptn in self.dictionary.pattern:
|
185
|
+
matcher = re.match(ptn['pattern'], text)
|
186
|
+
if matcher:
|
187
|
+
chosen_response = choice(ptn['phrases'])
|
188
|
+
return chosen_response.replace('%match%', matcher[0])
|
189
|
+
return choice(self._dictionary.random)
|
190
|
+
```
|
191
|
+
|
113
192
|
### 試したこと
|
114
193
|
同じエラーを探して参考しようとしたのですが(https://teratail.com/questions/139457)、この事例とは異なり引数の数が明らかに違うわけではないのでうまくいきません。もしかしたらエラーの箇所の付近の構文
|
115
194
|
```
|