使用不带按钮的pyqt5制作简单的聊天机器人

时间:2020-05-26 12:49:39

标签: python pyqt5

我想做一个最简单的聊天机器人。

目标-通过按键盘上的Enter键从单个textEdit获取输入,并在相同的textEdit上显示输出,例如控制台。

我的问题-无法将聊天机器人与Pyqt5 gui连接。

from PyQt5 import QtCore, QtGui, QtWidgets
from nltk.chat.util import Chat,reflections
from functools import partial
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(640, 480)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setObjectName("textEdit")
        self.gridLayout.addWidget(self.textEdit, 0, 0, 1, 1)
        #self.shortcut=QtGui.QShortcut(QtGui.QKeySequence("Return"),self)

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 25))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        self.textEdit.setPlainText("hello your welcome ask anything.Type 'quit' in lower case for leave")

        self.pairs = [
                [r"my name is (.*)",
                 ["Hello %1 , how are you today?",]],

                [r"(what is your name?|who are you?)",
                 ["my name is chhatty.\n And yours?"]],

                [r"(what is your (location|city)?|from where you are talking)",
                ["i am here, in front of you \n have you any sense same location as yours"]],

                [r"(you) are (.*)",
                 ["i am very very intelligent computer  \n %1 not %2 may be you are %2"]],

                 [r"is human (.*)",
                  [" i think human is not very intelligent but may be %1"]],

                  [r"(.*)",
                   ["what!\n Sorry,i can't understand "]]
                ] 

        self.chat =Chat(self.pairs,reflections)
        self.chat.converse()


if __name__ == "__main__":
    import sys
    app =QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

这在pyqt5上不起作用,我想在按Enter键时接受输入。

self.shortcut=QtGui.QShortcut(QtGui.QKeySequence("Return"),self)

以及如何将此聊天与textEdit连接起来。

 self.chat =Chat(self.pairs,reflections)
 self.chat.converse()

1 个答案:

答案 0 :(得分:3)

使用QTextEdit作为输入和输出很复杂,因为使用eventfilter可以在按Enter时检测到它,因此很难获得用户添加的文本,因为他可以修改文本的其他前一部分,除了其他问题

因此,我建议修改您的小部件,以使用户添加的文本通过QLineEdit。

要从聊天机器人获得响应,必须使用response()方法而不是converse()。

from PyQt5 import QtCore, QtGui, QtWidgets
from nltk.chat.util import Chat, reflections


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.output_te = QtWidgets.QTextEdit(readOnly=True)
        self.input_le = QtWidgets.QLineEdit(returnPressed=self.on_return_pressed)

        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)
        lay = QtWidgets.QVBoxLayout(central_widget)
        lay.addWidget(self.output_te)
        lay.addWidget(self.input_le)

        self.output_te.setPlainText(
            "hello your welcome ask anything.Type 'quit' in lower case for leave"
        )

        pairs = [
            [r"my name is (.*)", ["Hello %1 , how are you today?",]],
            [
                r"(what is your name?|who are you?)",
                ["my name is chhatty.\n And yours?"],
            ],
            [
                r"(what is your (location|city)?|from where you are talking)",
                [
                    "i am here, in front of you \n have you any sense same location as yours"
                ],
            ],
            [
                r"(you) are (.*)",
                ["i am very very intelligent computer  \n %1 not %2 may be you are %2"],
            ],
            [
                r"is human (.*)",
                [" i think human is not very intelligent but may be %1"],
            ],
            [r"(.*)", ["what!\n Sorry,i can't understand "]],
        ]

        self._chat = Chat(pairs, reflections)

    @property
    def chat(self):
        return self._chat

    @QtCore.pyqtSlot()
    def on_return_pressed(self):
        text = self.input_le.text()
        if text:
            res = self.chat.respond(text)
            self.output_te.append("[me]: {}".format(text))
            self.output_te.append("[bot]: {}".format(res))
            self.input_le.clear()


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())