从JavaScript代码调用Python函数

发布于 2021-01-29 17:32:33

我想从JavaScript代码中调用Python函数,因为JavaScript中没有其他方法可以做我想做的事情。这可能吗?您可以调整以下代码段使其正常工作吗?

JavaScript代码:

var tag = document.getElementsByTagName("p")[0];
text = tag.innerHTML;
// Here I would like to call the Python interpreter with Python function
arrOfStrings = openSomehowPythonInterpreter("~/pythoncode.py", "processParagraph(text)");

~/pythoncode.py 包含使用高级库的函数,这些函数在JavaScript中不具有易于编写的等效项:

import nltk # is not in JavaScript
def processParagraph(text):
  ...
  nltk calls
  ...
  return lst # returns a list of strings (will be converted to JavaScript array)
关注者
0
被浏览
167
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您需要做的就是向您的pythoncode发出ajax请求。您可以使用jquery
    http://api.jquery.com/jQuery.ajax/进行此操作,也可以仅使用javascript

    $.ajax({
      type: "POST",
      url: "~/pythoncode.py",
      data: { param: text}
    }).done(function( o ) {
       // do something
    });
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看