Analisi del sentiment in un file Cloud Storage
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Ispeziona un file archiviato in Cloud Storage e identifica l'opinione emotiva prevalente all'interno del testo.
Per saperne di più
Per la documentazione dettagliata che include questo esempio di codice, vedi quanto segue:
Esempio di codice
Salvo quando diversamente specificato, i contenuti di questa pagina sono concessi in base alla licenza Creative Commons Attribution 4.0, mentre gli esempi di codice sono concessi in base alla licenza Apache 2.0. Per ulteriori dettagli, consulta le norme del sito di Google Developers. Java è un marchio registrato di Oracle e/o delle sue consociate.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","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)."]]