1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【初心者向け】Pythonで簡単なChatbotを作る

Posted at

はじめに

今回は今更ながら初心者の方(私も含む)でも作れる最もシンプルなChatbotを作成した備忘録になります。


Chatbotの基本とは?

Chatbotについて簡単におさらいします。

「入力(ユーザーの発言)」に対して、
「決まったルール or ロジック」で返答するプログラム」

となります。

それでは、最初のステップでは「決まったキーワードに反応するルールベース」のbotを作ります。


最も簡単なChatbotを作ろう

まずは、決まったパターンに反応するbotです。

def simple_chat():
    print("BOT: こんにちは!何か話しかけてください(終了するには 'bye' と入力)")
    
    while True:
        user_input = input("あなた: ")

        if user_input.lower() == "bye":
            print("BOT: バイバイ!またね。")
            break
        elif "こんにちは" in user_input:
            print("BOT: こんにちは!元気ですか?")
        elif "名前" in user_input:
            print("BOT: 私はPythonで作られたBOTです。")
        elif "天気" in user_input:
            print("BOT: 今日の天気はどうでしょうね?")
        else:
            print("BOT: うーん、よくわかりません…")

simple_chat()

コードのポイント解説

input()

ユーザーから入力を受け取ります。

user_input = input("あなた: ")
.lower()

大文字・小文字の違いを無視して「bye」と判定できるようにします。

if user_input.lower() == "bye":in

文字列の部分一致を使って簡単なキーワード検出をしています。

elif "こんにちは" in user_input:

botをちょっと進化させてみよう

辞書(dict)を使って、発言と返答をセットで管理するようにすれば、見通しの良いコードになります。

def keyword_chat():
    responses = {
        "こんにちは": "こんにちは!元気ですか?",
        "名前": "私はPythonで作られたBOTです。",
        "天気": "今日の天気はどうでしょうね?",
    }

    print("BOT: 話しかけてください(終了するには 'bye'")

    while True:
        user_input = input("あなた: ")

        if user_input.lower() == "bye":
            print("BOT: バイバイ!またね。")
            break

        response_found = False
        for keyword, reply in responses.items():
            if keyword in user_input:
                print(f"BOT: {reply}")
                response_found = True
                break

        if not response_found:
            print("BOT: ごめんなさい、よくわかりません。")
keyword_chat()

この方法なら、条件が多くなっても管理しやすいです!

さらに進化させるには?

以下のようなステップで本格的なBOTに近づけていけます:
• 自然言語処理(NLP)ライブラリの活用(例:nltk, spaCy, transformers)
• ChatGPT APIとの連携
• GUIやWebアプリへの組み込み(Tkinter, Flaskなど)

まとめ

Chatbotは、最初はシンプルでもOK。
大切なのは、「ユーザーの発言を受け取って、反応する」という基本の流れを理解することです。

私も、もっと精進して本格的なbotを作成したいと思うので、自然言語処理や機械学習にもチャレンジしてみようと思います。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?