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

2024-04-25 13:33:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

目标-按键盘上的“回车”按钮从单个文本编辑中获取输入,并在同一文本编辑类似的控制台上显示输出

我的问题-无法将聊天机器人与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()

Tags: fromimportselfyouischatareqtgui
1条回答
网友
1楼 · 发布于 2024-04-25 13:33:37

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

因此,我建议修改您的小部件,以便用户添加的文本通过QLineEdit进行编辑

要从聊天机器人获取响应,必须使用respond()方法,而不是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_())

相关问题 更多 >