node.js 和 python 的 NLP 聊天机器人

Chatbot with node.js and python for NLP

我实际上正在做一个聊天机器人项目,它必须说 2 种语言 (方言摩洛哥语和法语),我愿意用 node.js 构建机器人并将其托管在服务器中,然后从头开始使用 python 构建 NLP,然后使用 link 两种代码。

您知道如何将 python 代码集成到 node.js 代码吗?

您可以创建一个带有端点的 Express 服务器,调用您的 NLP 后端(用 Python 编写)并检索它们的输出。


如何实施

一些假设

在这里,我假设您打算将用户的输入文本从您的 NodeJS 服务器发送到您的 Python NLP 后端以进行翻译并作为有效响应发送回您的 NodeJS 服务器。

计划

假设您的 Express 服务器上有一个名为 http://localhost:3000/Morrocan_NLP?text=mytexttotranslate 的端点。我们将把查询参数 text = "mytexttotranslate" 提供给 Python 脚本,该脚本将在 /Morrocan_NLP 端点接收它。然后这个 Python 脚本将处理那段文本并将其发送回您的 NodeJS Express 服务器。

为此,您可以在 NodeJS Express 应用程序中设置一个有效的路由,然后使用子进程从中调用相关的Python脚本这是一个假设展示此交互的代码示例:

// Setting up your Express server
const express = require('express');
const app = express();

// Step 1: 
// Set up the /Morrocan_NLP Express route
app.get('/Morrocan_NLP', invokePythonMorrocanTranslator);

// Step 2: 
// Create a callback function that handles requests to the '/Morrocan_NLP' endpoint
function invokePythonMorrocanTranslator(req, res) {

    // Importing Node's 'child_process' module to spin up a child process. 
    // There are other ways to create a child process but we'll use the 
    // simple spawn function here.
    var spawn = require("child_process").spawn;

    // The spawned python process which takes 2 arguments, the name of the 
    // python script to invoke and the query parameter text = "mytexttotranslate"
    var process = spawn('python', 
        [
            "./morrocan_nlp.py"
            req.query.text
        ]
    );

    // Step 3:
    // Listen for data output from stdout, in this case, from "morrocan_nlp.py"
    process.stdout.on('data', function(data) {

        // Sends the output from "morrocan_nlp.py" back to the user
        res.send(data.toString());

    });

}

在你的 Python 脚本(只是一个假设的脚本)中,它进行名为 morrocan_nlp.py 的摩洛哥翻译,你将有类似这样的东西来接收和处理 NodeJS 服务器的查询和 return结果给它。

import sys

# This is how you'll receive the queries from your NodeJS server
# Notice that sys.argv[1] refers to the 2nd argument of the list passed 
# into the spawn('python', ...) function in your NodeJS server code above
text_from_node_server = str(sys.argv[1])

# perform_translation here is a function I made up that 
# translates any text into Morrocan
translated_text = perform_translation(text_from_node_server)

# return your processed text to the NodeJS server via stdout
print(translated_text)
sys.stdout.flush()


外部资源

这是 NodeJS 服务器 <--> Python 脚本之间通信的基本方式,但是,如果您正在构建 large-scale 应用程序,它可能不是最具扩展性和效率的方式.因此,我建议您参考 this article,其中包含一个 step-by-step 教程,介绍如何以其他更可靠的方式集成 NodeJS 和 Python。我真的希望这对您或任何其他阅读本文的人有所帮助!