首页 > 解决方案 > 使用 NLTK 将命令链接到聊天

问题描述

我正在构建一个简单的聊天机器人,并希望它在给出特定问题/答案时运行命令。

例如:聊天机器人:“今天我能为您做什么?” 用户:“打开谷歌”聊天机器人:“打开 www.google.com”聊天机器人运行 command = WebDriver.open('www.google.com')

当前用于测试的代码:(TKinter 仅用于测试,请忽略 tkinter 代码)

import nltk
from nltk.chat.util import Chat, reflections
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import tkinter
from tkinter import *

root = TK()

root.geometry(100x100+100+100)
root.title("Chatbot")

pairs = [

["Hi im (.*)",["hello %1, What can I do for you?"]],
["Open google",["opening www.google.com"]],+OpenG() ##### this is where I need help as concatenating commands does not work

]

def firstChatBot():
    print("Greetings! My name is Chatbot-T1, What is yours?.")
    Chatbot = Chat(pairs, reflections)
    Chatbot.converse()

def openG():
    print("Opening www.google.com")
    driver = webdriver.Chrome()
    driver.get("https://www.googe.com")

btn1 = Button(root, text="Chat", command=firstChatBot).grid(column=1, row=1)

root.mainloop()

标签: python-3.xtkinterselenium-chromedrivernltk

解决方案


nltk 中有 Chat 类的源代码,它没有运行函数的方法。

您必须使用此代码并更改方法response(and __init__) 来获取三个元素(pattern, response, function_name),而不是(pattern, response)和 run function_name()

然后你可以使用

["Open google", ["opening www.google.com"], open_google]

应该open_google没有(),其他问题应该None作为第三要素。

编辑:我添加matchcallback()所以现在功能问题和 al 匹配(.*),它可以检查有问题的内容。

我使用Open (.*)了所以回调可以检查其中的内容(.*)并运行不同的页面。写Open google就开www.gooogle.com,写Open so就开www.StackOverflow.com

import nltk
from nltk.chat.util import Chat, reflections
import re
import random
import webbrowser

class MyChat(Chat):

    def __init__(self, pairs, reflections={}):

        # add `z` because now items in pairs have three elements
        self._pairs = [(re.compile(x, re.IGNORECASE), y, z) for (x, y, z) in pairs]
        self._reflections = reflections
        self._regex = self._compile_reflections()

    def respond(self, str):

        # add `callback` because now items in pairs have three elements
        for (pattern, response, callback) in self._pairs:
            match = pattern.match(str)

            if match:

                resp = random.choice(response)
                resp = self._wildcards(resp, match)

                if resp[-2:] == '?.':
                    resp = resp[:-2] + '.'
                if resp[-2:] == '??':
                    resp = resp[:-2] + '?'

                # run `callback` if exists  
                if callback: # eventually: if callable(callback):
                    callback(match)

                return resp

# --- create function before `pairs` ---

#def open_google(match):
#    webbrowser.open('https://google.com')

def open_something(match):
    #webbrowser.open('https://google.com')
    groups = match.groups()
    if groups:
        if groups[0] == 'google':
            webbrowser.open('https://google.com')
        elif groups[0] == 'so':
            webbrowser.open('https://stackoverflow.com')
        else:
            print('What is "{}"?'.format(groups[0]))
    else:
        print("I don't know what to open")

# --- every question needs `callback` or `None`---

pairs = [
    ["Hi im (.*)", ["hello %1, What can I do for you?"], None],
#    ["Open google", ["opening www.google.com"], open_google],
    ["Open (.*)", ["opening something ..."], open_something],
]

print("Greetings! My name is Chatbot-T1, What is yours?.")
Chatbot = MyChat(pairs, reflections)
Chatbot.converse()

推荐阅读