I'd like to call a Python
function from Javascript
code, because there isn't an alternative in Javascript
for doing what I want. Is this possible? Could you adjust the below snippet to work?
Javascript part:
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
import nltk # is not in Javascript
def processParagraph(text):
...
nltk calls
...
return lst # returns a list of strings (will be converted to `Javascript` array)
From the
document.getElementsByTagName
I guess you are running the javascript in a browser.The traditional way to expose functionality to javascript running in the browser is calling a remote URL using AJAX. The X in AJAX is for XML, but nowadays everybody uses JSON instead of XML.
For example, using jQuery you can do something like:
You will need to implement a python webservice on the server side. For simple webservices I like to use Flask.
A typical implementation looks like:
You can run IronPython (kind of Python.Net) in the browser with silverlight, but I don't know if NLTK is available for IronPython.
All you need is to make an ajax request to your pythoncode. You can do this with jquery http://api.jquery.com/jQuery.ajax/, or use just javascript
You cannot run .py files from JavaScript without the Python program like you cannot open .txt files without a text editor. But the whole thing becomes a breath with a help of a Web API Server (IIS in the example below).
Install python and create a sample file test.py
Create a method in your Web API Server
And now for your JavaScript:
Remember that your .py file won't run on your user's computer, but instead on the server.
Typically you would accomplish this using an ajax request that looks like