ניתוח סנטימנטים

ניתוח סנטימנטים בודק את הטקסט הנתון ומזהה את הדעה הרגשית הרווחת בטקסט, במיוחד כדי לקבוע אם הגישה של הכותב חיובית, שלילית או ניטרלית. ניתוח הסנטימנטים מתבצע באמצעות השיטה analyzeSentiment. במאמר תמיכה בשפות מפורטות השפות שנתמכות ב-Natural Language API. כדי להבין איך לפרש את ערכי הסנטימנט score ו-magnitude שנכללים בניתוח, קראו את המאמר פירוש ערכי ניתוח סנטימנטים.

בקטע הזה מוצגות כמה דרכים לזיהוי סנטימנט במסמך. צריך לשלוח בקשה נפרדת לכל מסמך.

ניתוח סנטימנט במחרוזת

הנה דוגמה לניתוח סנטימנטים במחרוזת טקסט שנשלחה ישירות ל-Natural Language API:

פרוטוקול

כדי לנתח את הסנטימנט במסמך, שולחים בקשת POST ל-method‏ documents:analyzeSentiment ב-REST ומספקים את גוף הבקשה המתאים, כמו בדוגמה הבאה.

בדוגמה הזו משתמשים בפקודה gcloud auth application-default print-access-token כדי לקבל אסימון גישה לחשבון שירות שמוגדר לפרויקט באמצעות ה-CLI של gcloud ב-Google Cloud Platform. במדריך למתחילים מוסבר איך להתקין את ה-CLI של gcloud ולהגדיר פרויקט עם חשבון שירות.

curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'encodingType': 'UTF8',
  'document': {
    'type': 'PLAIN_TEXT',
    'content': 'Enjoy your vacation!'
  }
}" "https://language.googleapis.com/v2/documents:analyzeSentiment"

אם לא תציינו את document.language_code, השפה תזוהה באופן אוטומטי. במאמר תמיכה בשפות מפורטות השפות שנתמכות ב-Natural Language API. מידע נוסף על הגדרת גוף הבקשה מופיע בDocument.

אם הבקשה תתבצע בהצלחה, השרת יחזיר קוד סטטוס 200 OK של HTTP ואת התשובה בפורמט JSON:

{
  "documentSentiment": {
    "magnitude": 0.8,
    "score": 0.8
  },
  "language": "en",
  "sentences": [
    {
      "text": {
        "content": "Enjoy your vacation!",
        "beginOffset": 0
      },
      "sentiment": {
        "magnitude": 0.8,
        "score": 0.8
      }
    }
  ]
}

documentSentiment.score מציין סנטימנט חיובי עם ערך גדול מאפס, וסנטימנט שלילי עם ערך קטן מאפס.

gcloud

פרטים נוספים זמינים בפקודה analyze-sentiment.

כדי לבצע ניתוח סנטימנטים, משתמשים ב-CLI של gcloud ובדגל --content כדי לזהות את התוכן שרוצים לנתח:

gcloud ml language analyze-sentiment --content="Enjoy your vacation!"

אם הבקשה מצליחה, השרת מחזיר תשובה בפורמט JSON:

{
  "documentSentiment": {
    "magnitude": 0.8,
    "score": 0.8
  },
  "language": "en",
  "sentences": [
    {
      "text": {
        "content": "Enjoy your vacation!",
        "beginOffset": 0
      },
      "sentiment": {
        "magnitude": 0.8,
        "score": 0.8
      }
    }
  ]
}

documentSentiment.score מציין סנטימנט חיובי עם ערך גדול מאפס, וסנטימנט שלילי עם ערך קטן מאפס.

Go

במאמר ספריות הלקוח של Natural Language מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Natural Language. מידע נוסף מופיע במאמרי העזרה של Natural Language Go API.

כדי לבצע אימות ב-שפה טבעית, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

	language "cloud.google.com/go/language/apiv2"
	"cloud.google.com/go/language/apiv2/languagepb"
)

// analyzeSentiment sends a string of text to the Cloud Natural Language API to
// assess the sentiment of the text.
func analyzeSentiment(w io.Writer, text string) error {
	ctx := context.Background()

	// Initialize client.
	client, err := language.NewClient(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	resp, err := client.AnalyzeSentiment(ctx, &languagepb.AnalyzeSentimentRequest{
		Document: &languagepb.Document{
			Source: &languagepb.Document_Content{
				Content: text,
			},
			Type: languagepb.Document_PLAIN_TEXT,
		},
		EncodingType: languagepb.EncodingType_UTF8,
	})

	if err != nil {
		return fmt.Errorf("AnalyzeSentiment: %w", err)
	}
	fmt.Fprintf(w, "Response: %q\n", resp)

	return nil
}

Java

במאמר ספריות הלקוח של Natural Language מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Natural Language. מידע נוסף מופיע במאמרי העזרה של Natural Language Java API.

כדי לבצע אימות ב-שפה טבעית, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Instantiate the Language client com.google.cloud.language.v2.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
  Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();
  AnalyzeSentimentResponse response = language.analyzeSentiment(doc);
  Sentiment sentiment = response.getDocumentSentiment();
  if (sentiment == null) {
    System.out.println("No sentiment found");
  } else {
    System.out.printf("Sentiment magnitude: %.3f\n", sentiment.getMagnitude());
    System.out.printf("Sentiment score: %.3f\n", sentiment.getScore());
  }
  return sentiment;
}

Python

במאמר ספריות הלקוח של Natural Language מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Natural Language. מידע נוסף מופיע במאמרי העזרה של Natural Language Python API.

כדי לבצע אימות ב-שפה טבעית, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import language_v2


def sample_analyze_sentiment(text_content: str = "I am so happy and joyful.") -> None:
    """
    Analyzes Sentiment in a string.

    Args:
      text_content: The text content to analyze.
    """

    client = language_v2.LanguageServiceClient()

    # text_content = 'I am so happy and joyful.'

    # Available types: PLAIN_TEXT, HTML
    document_type_in_plain_text = language_v2.Document.Type.PLAIN_TEXT

    # Optional. If not specified, the language is automatically detected.
    # For list of supported languages:
    # https://cloud.google.com/natural-language/docs/languages
    language_code = "en"
    document = {
        "content": text_content,
        "type_": document_type_in_plain_text,
        "language_code": language_code,
    }

    # Available values: NONE, UTF8, UTF16, UTF32
    # See https://cloud.google.com/natural-language/docs/reference/rest/v2/EncodingType.
    encoding_type = language_v2.EncodingType.UTF8

    response = client.analyze_sentiment(
        request={"document": document, "encoding_type": encoding_type}
    )
    # Get overall sentiment of the input document
    print(f"Document sentiment score: {response.document_sentiment.score}")
    print(f"Document sentiment magnitude: {response.document_sentiment.magnitude}")
    # Get sentiment for all sentences in the document
    for sentence in response.sentences:
        print(f"Sentence text: {sentence.text.content}")
        print(f"Sentence sentiment score: {sentence.sentiment.score}")
        print(f"Sentence sentiment magnitude: {sentence.sentiment.magnitude}")

    # Get the language of the text, which will be the same as
    # the language specified in the request or, if not specified,
    # the automatically-detected language.
    print(f"Language of the text: {response.language_code}")

שפות נוספות

C#‎: פעלו לפי הוראות ההגדרה של C# ‎ בדף ספריות הלקוח, ואז עיינו ב מאמרי העזרה של Natural Language ל-‎ .NET.

‫PHP: פועלים לפי הוראות ההגדרה של PHP בדף ספריות הלקוח, ואז נכנסים אל מאמרי העזרה של שפה טבעית ל-PHP.

‫Ruby: פועלים לפי הוראות ההגדרה של Ruby בדף ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Natural Language ל-Ruby.

ניתוח סנטימנטים מ-Cloud Storage

לנוחיותכם, Natural Language API יכול לבצע ניתוח סנטימנטים ישירות בקובץ שנמצא ב-Cloud Storage, בלי שתצטרכו לשלוח את תוכן הקובץ בגוף הבקשה.

הנה דוגמה לביצוע ניתוח סנטימנטים בקובץ שנמצא ב-Cloud Storage.

פרוטוקול

כדי לנתח את הסנטימנט במסמך שמאוחסן ב-Cloud Storage, שולחים בקשת POST ל-method‏ documents:analyzeSentiment ב-REST, ומספקים את גוף הבקשה המתאים עם הנתיב למסמך, כמו בדוגמה הבאה.

curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'document':{
    'type':'PLAIN_TEXT',
    'gcsContentUri':'gs://<bucket-name>/<object-name>'
  }
}" "https://language.googleapis.com/v2/documents:analyzeSentiment"

אם לא תציינו את document.language_code, השפה תזוהה באופן אוטומטי. במאמר תמיכה בשפות מפורטות השפות שנתמכות ב-Natural Language API. מידע נוסף על הגדרת גוף הבקשה מופיע בDocument.

אם הבקשה תתבצע בהצלחה, השרת יחזיר קוד סטטוס 200 OK של HTTP ואת התשובה בפורמט JSON:

{
  "documentSentiment": {
    "magnitude": 0.8,
    "score": 0.8
  },
  "language_code": "en",
  "sentences": [
    {
      "text": {
        "content": "Enjoy your vacation!",
        "beginOffset": 0
      },
      "sentiment": {
        "magnitude": 0.8,
        "score": 0.8
      }
    }
  ]
}

documentSentiment.score מציין סנטימנט חיובי עם ערך גדול מאפס, וסנטימנט שלילי עם ערך קטן מאפס.

gcloud

פרטים נוספים זמינים בפקודה analyze-sentiment.

כדי לבצע ניתוח סנטימנטים בקובץ ב-Cloud Storage, משתמשים בכלי שורת הפקודה gcloud ובדגל --content-file כדי לזהות את נתיב הקובץ שמכיל את התוכן לניתוח:

gcloud ml language analyze-sentiment --content-file=gs://YOUR_BUCKET_NAME/YOUR_FILE_NAME

אם הבקשה מצליחה, השרת מחזיר תשובה בפורמט JSON:

{
  "documentSentiment": {
    "magnitude": 0.8,
    "score": 0.8
  },
  "language": "en",
  "sentences": [
    {
      "text": {
        "content": "Enjoy your vacation!",
        "beginOffset": 0
      },
      "sentiment": {
        "magnitude": 0.8,
        "score": 0.8
      }
    }
  ]
}

documentSentiment.score מציין סנטימנט חיובי עם ערך גדול מאפס, וסנטימנט שלילי עם ערך קטן מאפס.

Go

במאמר ספריות הלקוח של Natural Language מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Natural Language. מידע נוסף מופיע במאמרי העזרה של Natural Language Go API.

כדי לבצע אימות ב-שפה טבעית, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


func analyzeSentimentFromGCS(ctx context.Context, gcsURI string) (*languagepb.AnalyzeSentimentResponse, error) {
	return client.AnalyzeSentiment(ctx, &languagepb.AnalyzeSentimentRequest{
		Document: &languagepb.Document{
			Source: &languagepb.Document_GcsContentUri{
				GcsContentUri: gcsURI,
			},
			Type: languagepb.Document_PLAIN_TEXT,
		},
	})
}

Java

במאמר ספריות הלקוח של Natural Language מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Natural Language. מידע נוסף מופיע במאמרי העזרה של Natural Language Java API.

כדי לבצע אימות ב-שפה טבעית, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Instantiate the Language client com.google.cloud.language.v2.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
  Document doc =
      Document.newBuilder().setGcsContentUri(gcsUri).setType(Type.PLAIN_TEXT).build();
  AnalyzeSentimentResponse response = language.analyzeSentiment(doc);
  Sentiment sentiment = response.getDocumentSentiment();
  if (sentiment == null) {
    System.out.println("No sentiment found");
  } else {
    System.out.printf("Sentiment magnitude : %.3f\n", sentiment.getMagnitude());
    System.out.printf("Sentiment score : %.3f\n", sentiment.getScore());
  }
  return sentiment;
}

Node.js

במאמר ספריות הלקוח של Natural Language מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Natural Language. מידע נוסף מופיע במאמרי העזרה של Natural Language Node.js API.

כדי לבצע אימות ב-שפה טבעית, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud client library
const language = require('@google-cloud/language').v2;

// Creates a client
const client = new language.LanguageServiceClient();

/**
 * TODO(developer): Uncomment the following lines to run this code
 */
// const bucketName = 'Your bucket name, e.g. my-bucket';
// const fileName = 'Your file name, e.g. my-file.txt';

// Prepares a document, representing a text file in Cloud Storage
const document = {
  gcsContentUri: `gs://${bucketName}/${fileName}`,
  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}`);
});

Python

במאמר ספריות הלקוח של Natural Language מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Natural Language. מידע נוסף מופיע במאמרי העזרה של Natural Language Python API.

כדי לבצע אימות ב-שפה טבעית, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import language_v2


def sample_analyze_sentiment(
    gcs_content_uri: str = "gs://cloud-samples-data/language/sentiment-positive.txt",
) -> None:
    """
    Analyzes Sentiment in text file stored in Cloud Storage.

    Args:
      gcs_content_uri: Google Cloud Storage URI where the file content is located.
        e.g. gs://[Your Bucket]/[Path to File]
    """

    client = language_v2.LanguageServiceClient()

    # Available types: PLAIN_TEXT, HTML
    document_type_in_plain_text = language_v2.Document.Type.PLAIN_TEXT

    # Optional. If not specified, the language is automatically detected.
    # For list of supported languages:
    # https://cloud.google.com/natural-language/docs/languages
    language_code = "en"
    document = {
        "gcs_content_uri": gcs_content_uri,
        "type_": document_type_in_plain_text,
        "language_code": language_code,
    }

    # Available values: NONE, UTF8, UTF16, UTF32
    # See https://cloud.google.com/natural-language/docs/reference/rest/v2/EncodingType.
    encoding_type = language_v2.EncodingType.UTF8

    response = client.analyze_sentiment(
        request={"document": document, "encoding_type": encoding_type}
    )
    # Get overall sentiment of the input document
    print(f"Document sentiment score: {response.document_sentiment.score}")
    print(f"Document sentiment magnitude: {response.document_sentiment.magnitude}")
    # Get sentiment for all sentences in the document
    for sentence in response.sentences:
        print(f"Sentence text: {sentence.text.content}")
        print(f"Sentence sentiment score: {sentence.sentiment.score}")
        print(f"Sentence sentiment magnitude: {sentence.sentiment.magnitude}")

    # Get the language of the text, which will be the same as
    # the language specified in the request or, if not specified,
    # the automatically-detected language.
    print(f"Language of the text: {response.language_code}")

שפות נוספות

C#‎: פעלו לפי הוראות ההגדרה של C# ‎ בדף ספריות הלקוח, ואז עיינו ב מאמרי העזרה של Natural Language ל-‎ .NET.

‫PHP: פועלים לפי הוראות ההגדרה של PHP בדף ספריות הלקוח, ואז נכנסים אל מאמרי העזרה של שפה טבעית ל-PHP.

‫Ruby: פועלים לפי הוראות ההגדרה של Ruby בדף ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Natural Language ל-Ruby.