我需要将值从PHP传递给Python脚本,然后将该值写入csv文件。但是,我遇到了困难,我的python在调用时写了一个空的csv文件。可能是什么问题。
<?php
if (isset($_POST['data'])){
$data = $_POST['data'];
$result = exec("python processData.py .$data");
echo $result;
}
?>
和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()
答案 0 :(得分:1)
$result = exec("python processData.py .$data");
输入时可能会出现问题:$data = "hello little world";
它会传递给
$result = exec("python processData.py .hello little world");
sys.argv将是
["processData.py",".hello","little","world"]
不幸的是,我不确定nltk将如何处理,但肯定不会像你想要的那样
作为旁白
d = [i.lower() for i in tokens if (not tokens in stopwords.words('english'))]
应该重写
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 = []
答案 1 :(得分:0)
在$ data之前可能是。,试试这个:
$result = exec("python processData.py {$data}");
问候!
答案 2 :(得分:0)
exec()
或其他任何内容都没有问题。问题是nltk
模块无法找到nltk_data
目录。对于它,只需找到系统中nltk_data
所在的位置:通常为~/nltk_data
。现在导入在运行该函数时添加该路径。
import nltk;
现在,nltk.data.path
是搜索模块的位置列表。你可以这样做:
nltk.data.path.append("your location/directory");