尝试在 Python(使用 nltk 和 flask)和 html 模板之间传递数据

Trying to pass data between Python(using nltk and flask) and a html template

我有一个 Python 代码,它使用 NLTK 和 Flask 创建一个在本地服务器上运行的聊天机器人。 在我 运行 或执行代码后,html 页面在本地服务器上打开,我提供了一个输入,但输入似乎没有传递到我的 python 代码。我的 python 控制台上出现一个提示,聊天机器人在其中接受输入和 运行s.

我对代码进行了很多修改,运行使用不同形式的代码大约 30-40 次,对其进行调试并进行了大量的反复试验。 下面的代码是唯一 运行 没有任何错误的代码,但是机器人在 Html 页面上显示的输出是 "none".

如有任何帮助或建议,我们将不胜感激。我是 Flask 和 NLTK 的新手。谢谢。

这是我的Python代码

from nltk.chat.util import Chat, reflections
from flask import Flask, render_template, request

pairs = [
    [
        r"my name is (.*)",
        ["Hello %1, How are you today ?", ]
    ],
    [
        r"how are you ?",
        ["I'm doing good\nHow about You ?", ]
    ],
    [
        r"sorry (.*)",
        ["Its alright", "Its OK, never mind", ]
    ],
    [
        r"hi|hey|hello",
        ["Hello", "Hey there", ]
    ],
]

app = Flask(__name__, template_folder='templates')

@app.route('/', methods=['GET', 'POST'])
def samplefunction():
    if request.method == 'GET':
        return render_template('new.html')
    if request.method == 'POST':
        greetIn = request.form['human']
        greetOut = c(greetIn)
        return render_template('new.html',bot1=greetOut)

def c(x):
  chat=Chat(pairs,reflections)
  return chat.converse(x)

if __name__ == '__main__':
    app. run(host='127.0.4.21', port=5000, debug=True)

使用的html模板是-new.html,如下:

<html>
  <head>
    <title>BOT</title>
    <script>
        var bot = {{ bot }}
    </script>
  </head>
  <body>
      <h1>Hello, type something to begin!</h1>
      <form method='post'>
        Human: <input type='text' name='human'><br>
        Bot1: {{bot1}}<br>
        <input type="submit" name="action">
      </form>
  </body>
</html>

尝试使用 chat.respond(x) 而不是 chat.converse。

我不得不更改 nltk.chat.util 包中的代码,并为 converse() 方法提供 return 类型,它最初只有一个打印语句而没有 return .

原代码是

def converse(self, quit="quit"):
        user_input = ""
        while user_input != quit:
            user_input = quit
            try:
                user_input = input(">")
            except EOFError:
                print(user_input)
            if user_input:
                while user_input[-1] in "!.":
                    user_input = user_input[:-1]
                print(self.respond(user_input))

更改后的代码:


def converse(self, quit="quit"):
        user_input = ""
        while user_input != quit:
            user_input = quit
            try:
                user_input = input(">")
            except EOFError:
                print(user_input)
            if user_input:
                while user_input[-1] in "!.":
                    user_input = user_input[:-1]
                return(self.respond(user_input))

我不得不删除打印语句并放置一个 return 方法。