首页 > 解决方案 > 如何将元组列表从 Python 传递到 PHP 脚本?

问题描述

我有一个 PHP 脚本(index.php),它需要调用一个 python 脚本(pos_tagger.py)并获取一个元组列表作为返回。我想将一个句子作为字符串从 PHP 脚本发送到 python 脚本。我希望 python 脚本将元组列表返回给 PHP 脚本。我试图将元组列表作为 JSON 数组返回。

在返回元组列表时,我在 PHP 变量中得到了 NULL。

PHP 脚本index.php的代码。

<?PHP

$sent = "I want to get tagged";
$command_exec = escapeshellcmd("python ./pos_tagger.py '$sent'");
$str_output = shell_exec($command_exec);

// This should contain the string
echo $str_output.'<br>';

// Use $arr to store the JSON array
$arr = json_decode($str_output);

?>

现在我将展示 2 个输出不同但我希望它是相同的案例。


案例 1 - pos_tagger.py

import sys
import nltk
import json

# nltk.download('averaged_perceptron_tagger')

def myfunc(sent):
    tagged = nltk.pos_tag(sent.split())
    return tagged

sent = sys.argv[1]
tagged_words = myfunc(sent)
ans = json.dumps(tagged_words)

print(ans)

这种情况下浏览器中的实际输出- 无(空白)

预期输出

[["I", "PRP"], ["want", "VBP"], ["to", "TO"], ["get", "VB"], ["tagged", "VBN"]]

可能的问题- $str_output 为 NULL。我无法理解这背后的原因。


案例 2 - pos_tagger.py - 传递硬编码的答案,它可以工作。

import json
print(json.dumps([("I", "PRP"), ("want", "VBP"), ("to", "TO"), ("get", "VB"), ("tagged", "VBN")]))

这种情况下浏览器中的实际输出:

[["I", "PRP"], ["want", "VBP"], ["to", "TO"], ["get", "VB"], ["tagged", "VBN"]]

如果有人可以提供帮助,将不胜感激!谢谢!

标签: pythonphpjsonshell

解决方案


我只是通过更改index.php中的一行来解决它

以前 Python 网络服务器是 2.x,但现在我使用 Python3 调用它,所以它变成了 python 3.x(更具体地说是 3.6.9),所以 NLTK 工作得很好,因为 nltk 工作我们需要 3.5+ 版本

<?PHP

$sent = "I want to get tagged";
$command_exec = escapeshellcmd("python3 ./pos_tagger.py '$sent'");
$str_output = shell_exec($command_exec);

// This should contain the string
echo $str_output.'<br>';

// Use $arr to store the JSON array
$arr = json_decode($str_output);

?>

推荐阅读