从PHP调用Python脚本并没有成功

时间:2015-08-02 14:14:09

标签: php python

我正在尝试使用python从文本或句子中提取主要关键字。我正在使用python's RAKE module。以下python代码在控制台中运行良好。但是,当我试图从PHP调用python脚本时,脚本不解析我存储在php变量中的任何新文本或句子,而是输出旧文本/句子,即使我在python脚本中注释掉它并用sys.argv[1]参数替换它。在各种方面,在PHP中我尝试使用PHP's exec and passthru commands没有任何运气来解决这个问题,所以我最终决定在这里发布我的问题。

PHP脚本

$var1 = 'The extra sleep will help your body wash out stress hormones.';

Technique(1)  
$output = exec("python rake_tutorial.py .$var1");

Technique(2)
$output = exec('python rake_tutorial.py ' .$var1, $result);

Technique(3)
$command = 'python rake_tutorial.py ' . $var1;
$output = passthru($command);

Technique(4) 
$output = exec("python rake_tutorial.py $var1", $result);
echo '<pre>' . print_r($result, true); 

这是我的Python代码

__author__ = 'a_medelyan'

import rake
import operator
import sys

# EXAMPLE ONE - SIMPLE
stoppath = "SmartStoplist.txt"

# EXAMPLE TWO - BEHIND THE SCENES (from https://github.com/aneesha/RAKE/rake.py)

# 1. initialize RAKE by providing a path to a stopwords file
rake_object = rake.Rake(stoppath)

# text = "What you use depends on your baby's age and physical development."



# 1. Split text into sentences
sentenceList = rake.split_sentences(text)



# generate candidate keywords
stopwordpattern = rake.build_stop_word_regex(stoppath)
phraseList = rake.generate_candidate_keywords(sentenceList, stopwordpattern)
print "Phrases:", phraseList

# calculate individual word scores
wordscores = rake.calculate_word_scores(phraseList)

# generate candidate keyword scores
keywordcandidates = rake.generate_candidate_keyword_scores(phraseList, wordscores)
for candidate in keywordcandidates.keys():
    print "Candidate: ", candidate, ", score: ", keywordcandidates.get(candidate)

# sort candidates by score to determine top-scoring keywords
sortedKeywords = sorted(keywordcandidates.iteritems(), key=operator.itemgetter(1), reverse=True)
totalKeywords = len(sortedKeywords)

# for example, you could just take the top third as the final keywords
for keyword in sortedKeywords[0:(totalKeywords / 3)]:
    print "Keyword: ", keyword[0], ", score: ", keyword[1]

print rake_object.run(sys.argv[1])
sys.stdout.flush()
# print rake_object.run(text)

2 个答案:

答案 0 :(得分:0)

看起来您的exec命令出错了。请尝试以下命令:

$var1 = 'The extra sleep will help your body wash out stress hormones.';
$output = exec("python rake.py '".$var1."'");

希望这有帮助!

答案 1 :(得分:0)

我只是想提一下,在php https://github.com/artofzen/RAKE-PHP中有一个RAKE实现