分析 Cloud Storage 檔案中的情緒
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
檢查儲存在 Cloud Storage 中的檔案,並識別文字中的主要情緒觀點。
深入探索
如需包含這個程式碼範例的詳細說明文件,請參閱下列內容:
程式碼範例
PHP
如要瞭解如何安裝及使用 Natural Language 的用戶端程式庫,請參閱這篇文章。
如要向 Natural Language 進行驗證,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","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)."]]