我有一个使用NLTK和Flask创建可在本地服务器上运行的聊天机器人的Python代码。在运行或执行代码后,将在本地服务器上打开html页面,并提供输入,但是输入似乎没有传递给我的python代码。我的python控制台上出现一个提示,聊天机器人将在其中进行输入并运行。
我对代码进行了很多修改,以各种形式运行它约30至40次,调试并进行了大量的试验和错误。下面的代码是唯一似乎没有任何错误运行的代码,但是bot在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>
我不得不更改nltk.chat.util包中的代码,并为converse()方法提供返回类型,它最初只有一条打印语句,没有返回。
原始代码为
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))
我必须删除打印语句并放入返回方法。
尝试使用chat.respond(x)代替chat.converse。