python - 如何将元组列表从 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"]]
如果有人可以提供帮助,将不胜感激!谢谢!
解决方案
我只是通过更改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);
?>
推荐阅读
- python-3.x - 根据 Condition Pandas Dataframe 拆分列数据
- c - 无限循环,程序忽略行
- java - 创建类 A.class 的模拟对象数组
- image - 如何使用 Dashboard 上传图像并使用 cloudinary 知道图像 URL?
- r - 如何在我的代码中停止 if 循环的计数过程?
- javascript - Electron - 创建文件时出现问题,错误“EROFS:只读文件系统”
- javascript - 如何使用 mvc 中的脚本保持 Timer 在后台运行
- php - 在 PHP 循环中计算多个纬度/经度之间的多个距离
- sql - SQL 链接词 - 双向关系
- python - 如果我们只有字符串类型的方法名称,有没有办法获取方法需要的参数数量?