how to call python scripts from php

≡放荡痞女 提交于 2019-12-11 12:04:57

问题


I need to pass a value from PHP to a Python script which then writes the value into a csv file. But, I'm having difficulties, my python when called writes an empty csv file. What could be the problem.

<?php
if (isset($_POST['data'])){
  $data = $_POST['data'];
  $result = exec("python processData.py .$data");
  echo $result;
  }                
 ?>

and processData.py

import nltk
from nltk.corpus import stopwords
from nltk import stem
import re   
import sys
import csv

mysentence = sys.argv[1]
f = open("output.csv", "wb")
tokens = nltk.word_tokenize(mysentence)
d = [i.lower() for i in tokens if (not tokens in stopwords.words('english'))]    
porter = nltk.PorterStemmer()
for t in tokens:
    result = porter.stem(t)    
    f.write(result+"\n")
    print result
f.close()

回答1:


$result = exec("python processData.py .$data");

is likely the problem if you typed : $data = "hello little world"; it woudl pass as

 $result = exec("python processData.py .hello little world");

sys.argv would be

  ["processData.py",".hello","little","world"]

unfortunately im not sure how nltk would handle that but surely not as you are intending

as an aside

d = [i.lower() for i in tokens if (not tokens in stopwords.words('english'))]  

should be rewriten

if  tokens not in stopwords.words('english'):
   d = [i.lower() for i in tokens]
else: #if your actually planning on using d anywhere ... currently your just throwing it out
      # not using d makes all of this just as effective as a pass statement
   d = []



回答2:


Maybe the . before $data, try this:

$result = exec("python processData.py {$data}");

Regards!




回答3:


There is no issue with the exec() or anything. The problem is that the nltk module is not able to locate the nltk_data directory. For it just locate where the nltk_data is present in your system: usually ~/nltk_data. Now import add that path when you run the function.

import nltk;

Now, nltk.data.path is a list of locations where to search for the modules. You can just do:

nltk.data.path.append("your location/directory");


来源:https://stackoverflow.com/questions/21864348/how-to-call-python-scripts-from-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!