Python 实现简单智能聊天机器人

yizhihongxing

Python 实现简单智能聊天机器人攻略

介绍

智能聊天机器人是指能够理解人类语言并进行智能回复的计算机程序,是自然语言处理(NLP)和人工智能(AI)技术的应用之一。Python 作为一种流行的编程语言,在实现智能聊天机器人方面表现出色。

本攻略将介绍如何使用 Python 实现一个简单的智能聊天机器人。

步骤

  1. 安装所需的 Python packages。
pip install nltk
pip install numpy
pip install tensorflow
pip install tflearn
  1. 导入所需的 packages。
import nltk
from nltk.stem.lancaster import LancasterStemmer
import numpy as np
import tflearn
import tensorflow as tf
import random
import json
import pickle
  1. 准备数据

准备一份包含了智能聊天机器人可能会遇到的所有问题及对应回答的 JSON 文件,是实现智能聊天机器人的最重要的一步。

  1. 对数据进行预处理

使用NLTK(自然语言工具包)进行文本的预处理,去除无用词汇,将文本转换为词汇列表。在预处理之后,将列表转换成按照每个词的出现次数统计的向量。

stemmer = LancasterStemmer()

def tokenize(sentence):
    return nltk.word_tokenize(sentence)

def stem(word):
    return stemmer.stem(word.lower())

def bag_of_words(tokenized_sentence, words):
    sentence_words = [stem(word) for word in tokenized_sentence]
    bag = np.zeros(len(words), dtype=np.float32)
    for idx, w in enumerate(words):
        if w in sentence_words:
            bag[idx] = 1.0
    return bag
  1. 构建机器学习模型

在预处理完成的基础上,将数据集分成输入和输出,使用 TensorFlow 和 tflearn 库在数据集上训练模型,并使用 pickle 序列化保存模型。

with open("intents.json") as file:
    data = json.load(file)

words = []
labels = []
docs_x = []
docs_y = []

for intent in data["intents"]:
    for pattern in intent["patterns"]:
        tokenized_sentence = tokenize(pattern)
        docs_x.append(bag_of_words(tokenized_sentence, words))
        docs_y.append(intent["tag"])
    if intent["tag"] not in labels:
        labels.append(intent["tag"])

words = [stem(word) for word in words]
words = sorted(list(set(words)))

labels = sorted(labels)

training_data = []
output_data = []

out_empty = [0 for _ in range(len(labels))]

for idx, x in enumerate(docs_x):
    training_data.append(x)
    output_data.append(out_empty.copy())
    output_data[idx][labels.index(docs_y[idx])] = 1

training_data = np.array(training_data)
output_data = np.array(output_data)

tf.reset_default_graph()

net = tflearn.input_data(shape=[None, len(training_data[0])])
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, len(output_data[0]), activation="softmax")
net = tflearn.regression(net)

model = tflearn.DNN(net)

model.fit(training_data, output_data, n_epoch=1000, batch_size=8, show_metric=True)
model.save("model.tflearn")

pickle.dump({"words": words, "labels": labels, "training_data": training_data, "output_data": output_data}, open("data.pickle", "wb"))
  1. 完整的聊天机器人代码样例
import nltk
from nltk.stem.lancaster import LancasterStemmer
import numpy as np
import tflearn
import tensorflow as tf
import random
import json
import pickle

stemmer = LancasterStemmer()

def tokenize(sentence):
    return nltk.word_tokenize(sentence)

def stem(word):
    return stemmer.stem(word.lower())

def bag_of_words(tokenized_sentence, words):
    sentence_words = [stem(word) for word in tokenized_sentence]
    bag = np.zeros(len(words), dtype=np.float32)
    for idx, w in enumerate(words):
        if w in sentence_words:
            bag[idx] = 1.0
    return bag

def chat():
    with open("intents.json") as file:
        data = json.load(file)

    with open("data.pickle", "rb") as f:
        words, labels, training_data, output_data = pickle.load(f)

    tf.reset_default_graph()

    net = tflearn.input_data(shape=[None, len(training_data[0])])
    net = tflearn.fully_connected(net, 8)
    net = tflearn.fully_connected(net, 8)
    net = tflearn.fully_connected(net, len(output_data[0]), activation="softmax")
    net = tflearn.regression(net)

    model = tflearn.DNN(net)

    model.load("model.tflearn")

    print("Let's chat! Enter 'quit' to exit")
    while True:
        user_input = input("You: ")
        if user_input.lower() == 'quit':
            break

        tokenized_input = tokenize(user_input)
        bag = bag_of_words(tokenized_input, words)

        results = model.predict([bag])[0]
        results_index = np.argmax(results)
        tag = labels[results_index]

        if results[results_index] > 0.7:
            for intent in data["intents"]:
                if intent["tag"] == tag:
                    response = random.choice(intent["responses"])
                    print("Bot: ", response)
        else:
            print("Bot: I'm not quite sure what you mean")

此时,聊天机器人已经构建完成,你可以运行 chat() 函数进行测试。

示例

以下是一个测试机器人的例子:

Let's chat! Enter 'quit' to exit
You: Hi there!
Bot: Hiya!

You: Can you help me with my order?
Bot: Of course, can you give me your order number?

You: Oh, I don't have it with me right now.
Bot: Sorry, I need your order number to help you.

You: Can you tell me about the return policy?
Bot: Our return policy is 30 days from the date of purchase. What item are you looking to return?

You: Thank you!
Bot: You're welcome!

如上例所示,智能聊天机器人可以理解并回答用户提出的关于订单、退货政策等问题,过程中表现出了不同程度的智能。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python 实现简单智能聊天机器人 - Python技术站

(0)
上一篇 2023年5月23日
下一篇 2023年5月23日

相关文章

  • 利用python实现汉字转拼音的2种方法

    关于“利用Python实现汉字转拼音的2种方法”这个话题,以下是我准备的详细攻略。 1. 什么是汉字转拼音 汉字转拼音即将汉字转化为拼音。在很多应用场景下,我们需要将输入的汉字转换成对应的拼音,方便进行后续处理和分析。下面介绍两种常用的汉字转拼音方法。 2. 利用pypinyin实现汉字转拼音 pypinyin是一个简单易用的Python库,可以方便地将汉字…

    python 2023年5月20日
    00
  • pip报错“ModuleNotFoundError: No module named ‘pip._vendor.urllib3’”怎么处理?

    当使用pip安装Python包时,可能会遇到“ModuleNotFoundError: No module named ‘pip._vendor.urllib3’”错误。这个错误通常是由于以下原因之一引起的: pip版本过低:如果您的pip版本过低,则会出现此错误。在这种情况下,需要升级pip版本以解决问题。 urllib3模块缺失:如果您的urllib3模…

    python 2023年5月4日
    00
  • 浅谈matplotlib中FigureCanvasXAgg的用法

    我们来详细讲解一下“浅谈matplotlib中FigureCanvasXAgg的用法”。 1. 什么是FigureCanvasXAgg 在matplotlib中,FigureCanvas是图形的绘制场所,它可以是一个屏幕、一个文件(PDF、SVG等)或者其他任何能够显示图形的设备。而FigureCanvasXAgg,则是指一个基于agg渲染器的具有交互功能的…

    python 2023年5月18日
    00
  • Python tkinter事件高级用法实例

    请允许我从以下几个方面来讲解Python tkinter事件高级用法实例的完整攻略。 简介 Python tkinter是一个用于图形用户界面编程的模块。在tkinter中,事件是很重要的概念,它可以使程序变得更加动态和交互,同时可以增强用户体验。在Python tkinter中,事件也有许多高级用法,例如延迟事件、绑定事件等。 延迟事件 延迟事件指的是,当…

    python 2023年6月5日
    00
  • python简单几步获取各种DOS命令显示的内容详解流程

    获取DOS命令输出内容是Python程序开发中常见需求,以下是Python简单几步获取各种DOS命令显示的内容的详解流程: 步骤一:导入subprocess模块 Python可以通过subprocess模块来执行操作系统命令,从而实现获取DOS命令输出内容的目的。因此在程序开发之前,需要先导入subprocess模块。 import subprocess 步…

    python 2023年6月2日
    00
  • Python正则表达式re模块讲解以及其案例举例

    Python正则表达式re模块讲解以及其案例举例 正则表达式是一种用于描述字符串模式的语言,可以用于配、查找、替换和分割。在Python中,可以使用re模块来使用正则表达式。本文将详细介绍Python中正则表达式的语法、字符集、转义字符以及常用函数,并提供两个示例说明。 正则表达式语法 正则表达式由普通字符和元字符组成,普通字符表示本身,而元字符有特殊的含义…

    python 2023年5月14日
    00
  • Python利用pdfplumber实现读取PDF写入Excel

    下面是“Python利用pdfplumber实现读取PDF写入Excel”的完整实例教程: 1. 安装pdfplumber和openpyxl 在使用pdfplumber和openpyxl前,需要先安装它们。可以使用pip命令安装: pip install pdfplumber openpyxl 2. 读取PDF文件 在使用pdfplumber读取PDF文件前…

    python 2023年5月14日
    00
  • python的pyecharts绘制各种图表详细(附代码)

    下面就是对于“Python的Pyecharts绘制各种图表详细(附代码)”的完整攻略。 1. Pyecharts简介 Pyecharts是基于echarts.js的Python可视化库,提供了一套接近终端用户直观的Python可视化支持。Pyecharts支持的图表类型非常多,包括:- 折线图- 柱状图- 散点图- 饼图- 地图- 热力图- 词云等等 2. …

    python 2023年6月6日
    00
合作推广
合作推广
分享本页
返回顶部