// Imports the Google Cloud client library
const language = require('@google-cloud/language');
// Creates a client
const client = new language.LanguageServiceClient();
/**
* TODO(developer): Uncomment the following line to run this code.
*/
// const text = 'Your text to analyze, e.g. Hello, world!';
// Prepares a document, representing the provided text
const document = {
content: text,
type: 'PLAIN_TEXT',
};
// Detects the sentiment of the document
const [result] = await client.analyzeSentiment({document});
const sentiment = result.documentSentiment;
console.log('Document sentiment:');
console.log(` Score: ${sentiment.score}`);
console.log(` Magnitude: ${sentiment.magnitude}`);
const sentences = result.sentences;
sentences.forEach(sentence => {
console.log(`Sentence: ${sentence.text.content}`);
console.log(` Score: ${sentence.sentiment.score}`);
console.log(` Magnitude: ${sentence.sentiment.magnitude}`);
});
use Google\Cloud\Language\V1\Document;
use Google\Cloud\Language\V1\Document\Type;
use Google\Cloud\Language\V1\LanguageServiceClient;
/** Uncomment and populate these variables in your code */
// $text = 'The text to analyze.';
$languageServiceClient = new LanguageServiceClient();
try {
// Create a new Document, add text as content and set type to PLAIN_TEXT
$document = (new Document())
->setContent($text)
->setType(Type::PLAIN_TEXT);
// Call the analyzeSentiment function
$response = $languageServiceClient->analyzeSentiment($document);
$document_sentiment = $response->getDocumentSentiment();
// Print document information
printf('Document Sentiment:' . PHP_EOL);
printf(' Magnitude: %s' . PHP_EOL, $document_sentiment->getMagnitude());
printf(' Score: %s' . PHP_EOL, $document_sentiment->getScore());
printf(PHP_EOL);
$sentences = $response->getSentences();
foreach ($sentences as $sentence) {
printf('Sentence: %s' . PHP_EOL, $sentence->getText()->getContent());
printf('Sentence Sentiment:' . PHP_EOL);
$sentiment = $sentence->getSentiment();
if ($sentiment) {
printf('Entity Magnitude: %s' . PHP_EOL, $sentiment->getMagnitude());
printf('Entity Score: %s' . PHP_EOL, $sentiment->getScore());
}
print(PHP_EOL);
}
} finally {
$languageServiceClient->close();
}