Analyze sentiment in a Cloud Storage file
Stay organized with collections
Save and categorize content based on your preferences.
Inspect a file stored in Cloud Storage and identify the prevailing emotional opinion within the text.
Explore further
For detailed documentation that includes this code sample, see the following:
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],[],[],[],null,["# Analyze sentiment in a Cloud Storage file\n\nInspect a file stored in Cloud Storage and identify the prevailing emotional opinion within the text.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Analyzing Sentiment](/natural-language/docs/analyzing-sentiment)\n\nCode sample\n-----------\n\n### Go\n\n\nTo learn how to install and use the client library for Natural Language, see\n[Natural Language client libraries](/natural-language/docs/reference/libraries).\n\n\nFor more information, see the\n[Natural Language Go API\nreference documentation](/go/docs/reference/cloud.google.com/go/language/latest/apiv1).\n\n\nTo authenticate to Natural Language, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n func analyzeSentimentFromGCS(ctx context.Context, gcsURI string) (*languagepb.AnalyzeSentimentResponse, error) {\n \treturn client.AnalyzeSentiment(ctx, &languagepb.AnalyzeSentimentRequest{\n \t\tDocument: &languagepb.Document{\n \t\t\tSource: &languagepb.Document_GcsContentUri{\n \t\t\t\tGcsContentUri: gcsURI,\n \t\t\t},\n \t\t\tType: languagepb.Document_PLAIN_TEXT,\n \t\t},\n \t})\n }\n\n### Java\n\n\nTo learn how to install and use the client library for Natural Language, see\n[Natural Language client libraries](/natural-language/docs/reference/libraries).\n\n\nFor more information, see the\n[Natural Language Java API\nreference documentation](/java/docs/reference/google-cloud-language/latest/overview).\n\n\nTo authenticate to Natural Language, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n // Instantiate the Language client com.google.cloud.language.v2.LanguageServiceClient\n try (LanguageServiceClient language = LanguageServiceClient.create()) {\n Document doc =\n Document.newBuilder().setGcsContentUri(gcsUri).setType(Type.PLAIN_TEXT).build();\n AnalyzeSentimentResponse response = language.analyzeSentiment(doc);\n Sentiment sentiment = response.getDocumentSentiment();\n if (sentiment == null) {\n System.out.println(\"No sentiment found\");\n } else {\n System.out.printf(\"Sentiment magnitude : %.3f\\n\", sentiment.getMagnitude());\n System.out.printf(\"Sentiment score : %.3f\\n\", sentiment.getScore());\n }\n return sentiment;\n }\n\n### Node.js\n\n\nTo learn how to install and use the client library for Natural Language, see\n[Natural Language client libraries](/natural-language/docs/reference/libraries).\n\n\nFor more information, see the\n[Natural Language Node.js API\nreference documentation](/nodejs/docs/reference/language/latest).\n\n\nTo authenticate to Natural Language, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n // Imports the Google Cloud client library\n const language = require('https://cloud.google.com/nodejs/docs/reference/language/latest/overview.html').v2;\n\n // Creates a client\n const client = new language.https://cloud.google.com/nodejs/docs/reference/language/latest/overview.html();\n\n /**\n * TODO(developer): Uncomment the following lines to run this code\n */\n // const bucketName = 'Your bucket name, e.g. my-bucket';\n // const fileName = 'Your file name, e.g. my-file.txt';\n\n // Prepares a document, representing a text file in Cloud Storage\n const document = {\n gcsContentUri: `gs://${bucketName}/${fileName}`,\n type: 'PLAIN_TEXT',\n };\n\n // Detects the sentiment of the document\n const [result] = await client.analyzeSentiment({document});\n\n const sentiment = result.documentSentiment;\n console.log('Document sentiment:');\n console.log(` Score: ${sentiment.score}`);\n console.log(` Magnitude: ${sentiment.magnitude}`);\n\n const sentences = result.sentences;\n sentences.forEach(sentence =\u003e {\n console.log(`Sentence: ${sentence.text.content}`);\n console.log(` Score: ${sentence.sentiment.score}`);\n console.log(` Magnitude: ${sentence.sentiment.magnitude}`);\n });\n\n### PHP\n\n\nTo learn how to install and use the client library for Natural Language, see\n[Natural Language client libraries](/natural-language/docs/reference/libraries).\n\n\nTo authenticate to Natural Language, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n use Google\\Cloud\\Language\\V1\\AnalyzeSentimentRequest;\n use Google\\Cloud\\Language\\V1\\Client\\LanguageServiceClient;\n use Google\\Cloud\\Language\\V1\\Document;\n use Google\\Cloud\\Language\\V1\\Document\\Type;\n\n /**\n * @param string $uri The cloud storage object to analyze (gs://your-bucket-name/your-object-name)\n */\n function analyze_sentiment_from_file(string $uri): void\n {\n $languageServiceClient = new LanguageServiceClient();\n\n // Create a new Document, pass GCS URI and set type to PLAIN_TEXT\n $document = (new Document())\n -\u003esetGcsContentUri($uri)\n -\u003esetType(Type::PLAIN_TEXT);\n\n // Call the analyzeSentiment function\n $request = (new AnalyzeSentimentRequest())\n -\u003esetDocument($document);\n $response = $languageServiceClient-\u003eanalyzeSentiment($request);\n $document_sentiment = $response-\u003egetDocumentSentiment();\n // Print document information\n printf('Document Sentiment:' . PHP_EOL);\n printf(' Magnitude: %s' . PHP_EOL, $document_sentiment-\u003egetMagnitude());\n printf(' Score: %s' . PHP_EOL, $document_sentiment-\u003egetScore());\n printf(PHP_EOL);\n $sentences = $response-\u003egetSentences();\n foreach ($sentences as $sentence) {\n printf('Sentence: %s' . PHP_EOL, $sentence-\u003egetText()-\u003egetContent());\n printf('Sentence Sentiment:' . PHP_EOL);\n $sentiment = $sentence-\u003egetSentiment();\n if ($sentiment) {\n printf('Entity Magnitude: %s' . PHP_EOL, $sentiment-\u003egetMagnitude());\n printf('Entity Score: %s' . PHP_EOL, $sentiment-\u003egetScore());\n }\n print(PHP_EOL);\n }\n }\n\n### Python\n\n\nTo learn how to install and use the client library for Natural Language, see\n[Natural Language client libraries](/natural-language/docs/reference/libraries).\n\n\nFor more information, see the\n[Natural Language Python API\nreference documentation](/python/docs/reference/language/latest).\n\n\nTo authenticate to Natural Language, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n from google.cloud import language_v2\n\n\n def sample_analyze_sentiment(\n gcs_content_uri: str = \"gs://cloud-samples-data/language/sentiment-positive.txt\",\n ) -\u003e None:\n \"\"\"\n Analyzes Sentiment in text file stored in Cloud Storage.\n\n Args:\n gcs_content_uri: Google Cloud Storage URI where the file content is located.\n e.g. gs://[Your Bucket]/[Path to File]\n \"\"\"\n\n client = language_v2.LanguageServiceClient()\n\n # Available types: PLAIN_TEXT, HTML\n document_type_in_plain_text = language_v2.Document.Type.PLAIN_TEXT\n\n # Optional. If not specified, the language is automatically detected.\n # For list of supported languages:\n # https://cloud.google.com/natural-language/docs/languages\n language_code = \"en\"\n document = {\n \"gcs_content_uri\": gcs_content_uri,\n \"type_\": document_type_in_plain_text,\n \"language_code\": language_code,\n }\n\n # Available values: NONE, UTF8, UTF16, UTF32\n # See https://cloud.google.com/natural-language/docs/reference/rest/v2/EncodingType.\n encoding_type = language_v2.EncodingType.UTF8\n\n response = client.https://cloud.google.com/python/docs/reference/language/latest/google.cloud.language_v1.services.language_service.LanguageServiceClient.html#google_cloud_language_v1_services_language_service_LanguageServiceClient_analyze_sentiment(\n request={\"document\": document, \"encoding_type\": encoding_type}\n )\n # Get overall sentiment of the input document\n print(f\"Document sentiment score: {response.document_sentiment.score}\")\n print(f\"Document sentiment magnitude: {response.document_sentiment.magnitude}\")\n # Get sentiment for all sentences in the document\n for sentence in response.sentences:\n print(f\"Sentence text: {sentence.text.content}\")\n print(f\"Sentence sentiment score: {sentence.sentiment.score}\")\n print(f\"Sentence sentiment magnitude: {sentence.sentiment.magnitude}\")\n\n # Get the language of the text, which will be the same as\n # the language specified in the request or, if not specified,\n # the automatically-detected language.\n print(f\"Language of the text: {response.language_code}\")\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=language)."]]