Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

javascript - 从JavaScript代码调用Python函数(Call Python function from JavaScript code)

I'd like to call a Python function from JavaScript code, because there isn't an alternative in JavaScript for doing what I want.

(我想从JavaScript代码中调用Python函数,因为JavaScript中没有其他方法可以做我想做的事情。)

Is this possible?

(这可能吗?)

Could you adjust the below snippet to work?

(您可以调整以下代码段使其正常工作吗?)

JavaScript code:

(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 contains functions using advanced libraries that don't have an easy to write equivalent in JavaScript:

(~/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)
  ask by xralf translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All you need is to make an ajax request to your pythoncode.

(您需要做的就是向您的pythoncode发出ajax请求。)

You can do this with jquery http://api.jquery.com/jQuery.ajax/ , or use just javascript

(您可以使用jquery http://api.jquery.com/jQuery.ajax/进行此操作,也可以仅使用javascript)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...