Esta página se ha traducido con Cloud Translation API.
Switch to English

Clasifica texto

Analiza texto y muestra una lista de categorías de contenido que se aplican al texto.

Páginas de documentación que incluyen esta muestra de código

Para ver la muestra de código usada en contexto, consulta la siguiente documentación:

Muestra de código


        private static void ClassifyTextFromText(string text)
            var client = LanguageServiceClient.Create();
            var response = client.ClassifyText(new Document()
                Content = text,
                Type = Document.Types.Type.PlainText

        private static void WriteCategories(IEnumerable<ClassificationCategory> categories)
            foreach (var category in categories)
                Console.WriteLine($"\tCategory: {category.Name}");
                Console.WriteLine($"\t\tConfidence: {category.Confidence}");


func classifyText(ctx context.Context, client *language.Client, text string) (*languagepb.ClassifyTextResponse, error) {
	return client.ClassifyText(ctx, &languagepb.ClassifyTextRequest{
		Document: &languagepb.Document{
			Source: &languagepb.Document_Content{
				Content: text,
			Type: languagepb.Document_PLAIN_TEXT,


// Instantiate the Language client
try (LanguageServiceClient language = LanguageServiceClient.create()) {
  // set content to the text string
  Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();
  ClassifyTextRequest request = ClassifyTextRequest.newBuilder().setDocument(doc).build();
  // detect categories in the given text
  ClassifyTextResponse response = language.classifyText(request);

  for (ClassificationCategory category : response.getCategoriesList()) {
        "Category name : %s, Confidence : %.3f\n",
        category.getName(), category.getConfidence());


// 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',

// Classifies text in the document
const [classification] = await client.classifyText({document});
classification.categories.forEach(category => {
  console.log(`Name: ${}, Confidence: ${category.confidence}`);


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.';

// Make sure we have enough words (20+) to call classifyText
if (str_word_count($text) < 20) {
    printf('20+ words are required to classify text.' . PHP_EOL);
$languageServiceClient = new LanguageServiceClient();
try {
    // Create a new Document, add text as content and set type to PLAIN_TEXT
    $document = (new Document())

    // Call the analyzeSentiment function
    $response = $languageServiceClient->classifyText($document);
    $categories = $response->getCategories();
    // Print document information
    foreach ($categories as $category) {
        printf('Category Name: %s' . PHP_EOL, $category->getName());
        printf('Confidence: %s' . PHP_EOL, $category->getConfidence());
} finally {


from import language_v1

def sample_classify_text(text_content):
    Classifying Content in a String

      text_content The text content to analyze. Must include at least 20 words.

    client = language_v1.LanguageServiceClient()

    # text_content = 'That actor on TV makes movies in Hollywood and also stars in a variety of popular new TV shows.'

    # Available types: PLAIN_TEXT, HTML
    type_ = language_v1.Document.Type.PLAIN_TEXT

    # Optional. If not specified, the language is automatically detected.
    # For list of supported languages:
    language = "en"
    document = {"content": text_content, "type_": type_, "language": language}

    response = client.classify_text(request = {'document': document})
    # Loop through classified categories returned from the API
    for category in response.categories:
        # Get the name of the category representing the document.
        # See the predefined taxonomy of categories:
        print(u"Category name: {}".format(
        # Get the confidence. Number representing how certain the classifier
        # is that this category represents the provided text.
        print(u"Confidence: {}".format(category.confidence))


# text_content = "Text to classify"

require "google/cloud/language"

language = Google::Cloud::Language.language_service

document = { content: text_content, type: :PLAIN_TEXT }
response = language.classify_text document: document

categories = response.categories

categories.each do |category|
  puts "Name: #{} Confidence: #{category.confidence}"