The Python script:
# analyse_string.py
#!/usr/bin/python
import sys
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyser = SentimentIntensityAnalyzer()
print(str(analyser.polarity_scores(sys.argv[1])))
Laravel:
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
$text = 'The text you are desperate to analyze :)";
$process = new Process("python3 /Path/To/analyse_string.py \"{$text}\"");
$process->run();
// executes after the command finishes
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
echo $process->getOutput();
// Result (string): {'neg': 0.204, 'neu': 0.531, 'pos': 0.265, 'compound': 0.1779}
The improved version
Laravel:
// $json = an encoded JSON string
$process = new Process("python3 /Path/To/analyse_json.py {$json}");
$process->run();
// executes after the command finishes
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
dump(json_decode($process->getOutput(), true));
The Python script
# analyse.json.py
#!/usr/bin/python
import sys
import json
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
x=sys.argv[1]
data=json.loads(x)
analyser = SentimentIntensityAnalyzer()
for item in data:
item['sentiment'] = analyser.polarity_scores(item['text'])
item.pop('text', None)
print(json.dumps(data))
使用 Laravel 读取命令行输出的另一个技巧
ob_start();
black_box_function_printing_to_command_line();
$output = ob_get_clean();