Skip to content

Instantly share code, notes, and snippets.

@Sotalbireo
Last active October 25, 2016 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sotalbireo/6471f6aa3b7af574f301996effe31a22 to your computer and use it in GitHub Desktop.
Save Sotalbireo/6471f6aa3b7af574f301996effe31a22 to your computer and use it in GitHub Desktop.
Pythonで作る人工無能キミくん(http://shikamohu.hatenablog.com/entry/2013/11/25/055108 )のPython3.x対応版です。
# coding: UTF-8
import sqlite3
import random
import sys
if __name__ == '__main__':
# データベースと接続、無ければ作成
con = sqlite3.connect("memory.db")
# cursorオブジェクトを作る
cur = con.cursor()
# テーブルの作成(存在しなければ)
sql = "create table if not exists unknown(word text)"
con.execute(sql)
# 無限ループ
while 1:
# キーボード入力の文字列を受け取る
# 注)Python2とPython3の間でこの辺りの仕様が大幅に変更されました
#   以下のコメントアウトされた関数では動かない。たぶん。
#   str = raw_input("you : ").decode(sys.stdin.encoding)
str = input("you : ")
# 入力文字列が「さようなら」なら終了
if str == u"さようなら":
# 注)printの実装も変わった
#   Py2: print u"text" -> Py3: print("text")
print("kimi: バイバイ")
print("アプリケーションを終了しました")
break
# 入力文字列をデータベースのunknownテーブルに保存
sql = "insert into unknown values('%s')" % (str)
con.execute(sql)
# unknownテーブルのwordを取得
cur.execute(u"select * from unknown")
words = []
# wordsリストにすべてのwordを入れる
for row in cur: # rowはタプル
words.append(row[0]) # row[0]は1列目のwordの列を意味する。
# wordsリストからランダムに発言する
print("kimi: " + random.choice(words))
# コミット(=発言履歴をDBに保存)して、とじる
con.commit()
con.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment