JSON与python聊天机器人

aydmsdu9  于 2023-01-27  发布在  Python
关注(0)|答案(1)|浏览(171)

我有一个蹩脚的机器学习聊天机器人,我训练使用一些JSON数据。对于一些不同的事情,你可以要求机器人有一个适当的响应列表的请求。我的问题是搞清楚该怎么做的那些没有。对于那些人的我有python函数,我想运行在响应给定的某个命令。有没有什么办法可以做到,因为我知道在JSON中你不能传递函数。

{"intents": [
  {"tag": "greeting",
  "patterns": ["Hi", "Hello", "What's up", "Hey", "Hola", "Howdy"],
  "responses": ["Hi", "Hello", "What's up", "Hey", "How can I help", "Hi there", "What can I do for you"]
  },
  {"tag": "goodbye",
     "patterns": ["Bye", "See you later", "Goodbye", "later", "farewell", "bye-bye", "so long"],
     "responses": ["See you later", "Have a nice day", "Bye", "Goodbye"]
  },
  {"tag": "time",
   "patterns": ["What time is it", "What's the time", "time please"],
   "responses": []

一个python函数的示例

from datetime import datetime
from datetime import date

def simple(text):
    if text == "what time is it":
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")
        print("Current Time =", current_time)

这里还有机器学习方面的完整代码

import nltk
from nltk.stem.lancaster import LancasterStemmer
stemmer = LancasterStemmer()

import numpy
import tflearn
import tensorflow
import random
import json
import pickle

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

try:
    with open("data.pickle", "rb") as f:
        words, labels, training, output = pickle.load(f)
except:
    words = []
    labels = []
    docs_x = []
    docs_y = []

    for intent in data["intents"]:
        for pattern in intent["patterns"]:
            wrds = nltk.word_tokenize(pattern)
            words.extend(wrds)
            docs_x.append(wrds)
            docs_y.append(intent["tag"])

        if intent["tag"] not in labels:
            labels.append(intent["tag"])

    words = [stemmer.stem(w.lower()) for w in words if w != "?"]
    words = sorted(list(set(words)))

    labels = sorted(labels)

    training = []
    output = []

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

    for x, doc in enumerate(docs_x):
        bag = []

        wrds = [stemmer.stem(w.lower()) for w in doc]

        for w in words:
            if w in wrds:
                bag.append(1)
            else:
                bag.append(0)

        output_row = out_empty[:]
        output_row[labels.index(docs_y[x])] = 1

        training.append(bag)
        output.append(output_row)

    training = numpy.array(training)
    output = numpy.array(output)

    with open("data.pickle", "wb") as f:
        pickle.dump((words, labels, training, output), f)

tensorflow.compat.v1.reset_default_graph()

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

model = tflearn.DNN(net)

try:
    model.load("model.tflearn")
except:
    model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True)
    model.save("model.tflearn")

def bag_of_words(s, words):
    bag = [0 for _ in range(len(words))]

    s_words = nltk.word_tokenize(s)
    s_words = [stemmer.stem(word.lower()) for word in s_words]

    for se in s_words:
        for i, w in enumerate(words):
            if w == se:
                bag[i] = 1

    return numpy.array(bag)

def chat():
    print("Start talking with the bot (type quit to stop)!")
    while True:
        inp = input("You: ")
        if inp.lower() == "quit":
            break

        results = model.predict([bag_of_words(inp, words)])[0]
        results_index = numpy.argmax(results)
        tag = labels[results_index]

        if results[results_index] > 0.7:
            for tg in data["intents"]:
                if tg['tag'] == tag:
                    responses = tg['responses']

            print(random.choice(responses))
        else:
            print("I'm not sure what you want")

chat()
az31mfrm

az31mfrm1#

一个简单的方法是这样做:“如果你预测的'tag'是(例如)'time' do foo()。
在您的代码中,它看起来像这样:

def chat():
    print("Start talking with the bot (type quit to stop)!")
    
    while True:
        inp = input("You: ")
        if inp.lower() == "quit":
            break

        results = model.predict([bag_of_words(inp, words)])[0]
        results_index = numpy.argmax(results)
        tag = labels[results_index]

       if results[results_index] > 0.7:
            for tg in data["intents"]:
                if tg['tag'] == tag:
                    responses = tg['responses']
                    if tg['tag'] == 'time':  # Input have triggered the 'time' tag.
                        foo()  # Execute "time" function or what ever you want.

        print(random.choice(responses))
    else:
        print("I'm not sure what you want")

chat()

例如,你可以创建一个函数,当机器人“理解”用户说了一些触发了“再见”标签的话时,停止infinit while循环。

相关问题