質問編集履歴

1

responderクラスのコード追加

2018/08/20 15:27

投稿

oka12
oka12

スコア8

test CHANGED
File without changes
test CHANGED
@@ -220,6 +220,164 @@
220
220
 
221
221
  ```
222
222
 
223
+ responder.py
224
+
225
+ ```
226
+
227
+ import re
228
+
229
+
230
+
231
+ from random import choice
232
+
233
+
234
+
235
+ class Responder:
236
+
237
+ """AIの応答を制御する思考エンジンの基底クラス。
238
+
239
+ 継承して使わなければならない。
240
+
241
+
242
+
243
+ メソッド:
244
+
245
+ response(str) -- ユーザーの入力strを受け取り、思考結果を返す
246
+
247
+
248
+
249
+ プロパティ:
250
+
251
+ name -- Responderオブジェクトの名前
252
+
253
+ """
254
+
255
+
256
+
257
+ def __init__(self, name, dictionary):
258
+
259
+ """文字列を受け取り、自身のnameに設定する。
260
+
261
+ 辞書dictionaryを受け取り、自身のdictionaryに保持する。"""
262
+
263
+ self._name = name
264
+
265
+ self._dictionary = dictionary
266
+
267
+
268
+
269
+ def response(self, *args):
270
+
271
+ """文字列を受け取り、思考した結果を返す。"""
272
+
273
+ pass
274
+
275
+
276
+
277
+ @property
278
+
279
+ def name(self):
280
+
281
+ """思考エンジンの名前"""
282
+
283
+ return self._name
284
+
285
+
286
+
287
+ class WhatResponder(Responder):
288
+
289
+ """AIの応答を制御する思考エンジンクラス。
290
+
291
+ 入力に対して疑問形で聞き返す。"""
292
+
293
+
294
+
295
+ def response(self, text):
296
+
297
+ """文字列textを受け取り、'{text}ってなに?'という形式で返す。"""
298
+
299
+ return '{}ってなに?'.format(text)
300
+
301
+
302
+
303
+ class RandomResponder(Responder):
304
+
305
+ """AIの応答を制御する思考エンジンクラス。
306
+
307
+ 登録された文字列からランダムなものを返す。
308
+
309
+ """
310
+
311
+
312
+
313
+
314
+
315
+ def __init__(self, name):
316
+
317
+ """文字列を受け取り、オブジェクトの名前に設定する。
318
+
319
+ 'dics_random.txt'ファイルから応答文字列のリストを読み込む。"""
320
+
321
+ super().__init__(name)
322
+
323
+ self.responses = []
324
+
325
+ with open('dics_random.txt', mode='r', encoding='utf-8') as f:
326
+
327
+ self._responses = [x for x in f.read().splitlines() if x]
328
+
329
+
330
+
331
+
332
+
333
+ def response(self, _):
334
+
335
+ """ユーザーからの入力は受け取るが、使用せずにランダムな応答を返す。"""
336
+
337
+ return choice()
338
+
339
+
340
+
341
+
342
+
343
+ @property
344
+
345
+ def name(self):
346
+
347
+ """思考エンジンの名前"""
348
+
349
+ return self._name
350
+
351
+
352
+
353
+ class PatternResponder(Responder):
354
+
355
+ """AIの応答を制御する思考エンジンクラス。
356
+
357
+ 登録されたパターンに反応し、関連する応答を返す。
358
+
359
+ """
360
+
361
+
362
+
363
+ def response(self, text):
364
+
365
+ """ユーザーの入力に合致するパターンがあれば、関連するフレーズを返す。"""
366
+
367
+ for ptn in self.dictionary.pattern:
368
+
369
+ matcher = re.match(ptn['pattern'], text)
370
+
371
+ if matcher:
372
+
373
+ chosen_response = choice(ptn['phrases'])
374
+
375
+ return chosen_response.replace('%match%', matcher[0])
376
+
377
+ return choice(self._dictionary.random)
378
+
379
+ ```
380
+
223
381
 
224
382
 
225
383
  ### 試したこと