Analyser la syntaxe

Alors que la plupart des méthodes de Natural Language analysent about un texte donné, la méthode analyzeSyntax inspecte la structure du langage lui-même. L'analyse syntaxique divise le texte donné en une série de phrases et de jetons (généralement des mots) et fournit des informations linguistiques sur ces jetons. Reportez-vous à la page Arbres de morphologie et de dépendance pour plus de détails sur l'analyse linguistique, et à la page Langues acceptées pour obtenir une liste des langues dont la syntaxe peut être analysée par l'API Natural Language.

Cette section décrit plusieurs manières de détecter la syntaxe au sein d'un document. Vous devez envoyer une demande distincte pour chaque document.

Analyser la syntaxe dans une chaîne

Voici un exemple d'analyse syntaxique sur une chaîne de texte envoyée directement à l'API Natural Language :

Protocole

Pour analyser la syntaxe d'un document, envoyez une requête POST à la méthode REST documents:analyzeSyntax et fournissez le corps de requête approprié, comme indiqué dans l'exemple suivant.

L'exemple utilise la commande gcloud auth application-default print-access-token pour obtenir un jeton d'accès pour un compte de service configuré pour le projet à l'aide de gcloud CLI de Google Cloud Platform. Pour obtenir des instructions d'installation de la gcloud CLI et configurer un projet avec un compte de service, consultez le guide de démarrage rapide.

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': 'Google, headquartered in Mountain View, unveiled the new Android phone at the Consumer Electronic Show.  Sundar Pichai said in his keynote that users love their new Android phones.'
  }
}" "https://language.googleapis.com/v1/documents:analyzeSyntax"

Si vous ne spécifiez pas document.language, la langue est automatiquement détectée. Pour plus d'informations sur les langues acceptées par l'API Natural Language, consultez la page Langues acceptées. Pour en savoir plus sur la configuration du corps de la requête, reportez-vous à la documentation de référence sur Document.

Si la requête aboutit, le serveur renvoie un code d'état HTTP 200 OK et la réponse au format JSON :

{
  "sentences": [
    {
      "text": {
        "content": "Google, headquartered in Mountain View, unveiled the new Android phone at the Consumer Electronic Show.",
        "beginOffset": 0
      }
    },
    {
      "text": {
        "content": "Sundar Pichai said in his keynote that users love their new Android phones.",
        "beginOffset": 105
      }
    }
  ],
  "tokens": [
    {
      "text": {
        "content": "Google",
        "beginOffset": 0
      },
      "partOfSpeech": {
        "tag": "NOUN",
        "aspect": "ASPECT_UNKNOWN",
        "case": "CASE_UNKNOWN",
        "form": "FORM_UNKNOWN",
        "gender": "GENDER_UNKNOWN",
        "mood": "MOOD_UNKNOWN",
        "number": "SINGULAR",
        "person": "PERSON_UNKNOWN",
        "proper": "PROPER",
        "reciprocity": "RECIPROCITY_UNKNOWN",
        "tense": "TENSE_UNKNOWN",
        "voice": "VOICE_UNKNOWN"
      },
      "dependencyEdge": {
        "headTokenIndex": 7,
        "label": "NSUBJ"
      },
      "lemma": "Google"
    },
    ...
    {
      "text": {
        "content": ".",
        "beginOffset": 179
      },
      "partOfSpeech": {
        "tag": "PUNCT",
        "aspect": "ASPECT_UNKNOWN",
        "case": "CASE_UNKNOWN",
        "form": "FORM_UNKNOWN",
        "gender": "GENDER_UNKNOWN",
        "mood": "MOOD_UNKNOWN",
        "number": "NUMBER_UNKNOWN",
        "person": "PERSON_UNKNOWN",
        "proper": "PROPER_UNKNOWN",
        "reciprocity": "RECIPROCITY_UNKNOWN",
        "tense": "TENSE_UNKNOWN",
        "voice": "VOICE_UNKNOWN"
      },
      "dependencyEdge": {
        "headTokenIndex": 20,
        "label": "P"
      },
      "lemma": "."
    }
  ],
  "language": "en"
}

Le tableau tokens contient des objets Token représentant les jetons de phrases détectés, qui incluent des informations telles que la partie vocale du jeton et sa position dans la phrase.

gcloud

Reportez-vous à la commande analyze-syntax pour obtenir tous les détails.

Pour effectuer une analyse syntaxique, utilisez gcloud CLI et utilisez l'option --content pour identifier le contenu à analyser :

gcloud ml language analyze-syntax --content="Google, headquartered in Mountain View, unveiled the new Android phone at the Consumer Electronic Show.  Sundar Pichai said in his keynote that users love their new Android phones."

Si la requête aboutit, le serveur renvoie une réponse au format JSON :

{
  "sentences": [
    {
      "text": {
        "content": "Google, headquartered in Mountain View, unveiled the new Android phone at the Consumer Electronic Show.",
        "beginOffset": 0
      }
    },
    {
      "text": {
        "content": "Sundar Pichai said in his keynote that users love their new Android phones.",
        "beginOffset": 105
      }
    }
  ],
  "tokens": [
    {
      "text": {
        "content": "Google",
        "beginOffset": 0
      },
      "partOfSpeech": {
        "tag": "NOUN",
        "aspect": "ASPECT_UNKNOWN",
        "case": "CASE_UNKNOWN",
        "form": "FORM_UNKNOWN",
        "gender": "GENDER_UNKNOWN",
        "mood": "MOOD_UNKNOWN",
        "number": "SINGULAR",
        "person": "PERSON_UNKNOWN",
        "proper": "PROPER",
        "reciprocity": "RECIPROCITY_UNKNOWN",
        "tense": "TENSE_UNKNOWN",
        "voice": "VOICE_UNKNOWN"
      },
      "dependencyEdge": {
        "headTokenIndex": 7,
        "label": "NSUBJ"
      },
      "lemma": "Google"
    },
    ...
    {
      "text": {
        "content": ".",
        "beginOffset": 179
      },
      "partOfSpeech": {
        "tag": "PUNCT",
        "aspect": "ASPECT_UNKNOWN",
        "case": "CASE_UNKNOWN",
        "form": "FORM_UNKNOWN",
        "gender": "GENDER_UNKNOWN",
        "mood": "MOOD_UNKNOWN",
        "number": "NUMBER_UNKNOWN",
        "person": "PERSON_UNKNOWN",
        "proper": "PROPER_UNKNOWN",
        "reciprocity": "RECIPROCITY_UNKNOWN",
        "tense": "TENSE_UNKNOWN",
        "voice": "VOICE_UNKNOWN"
      },
      "dependencyEdge": {
        "headTokenIndex": 20,
        "label": "P"
      },
      "lemma": "."
    }
  ],
  "language": "en"
}

Le tableau tokens contient des objets Token représentant les jetons de phrases détectés, qui incluent des informations telles que la partie vocale du jeton et sa position dans la phrase.

Go

Pour savoir comment installer et utiliser la bibliothèque cliente pour Natural Language, consultez la page Bibliothèques clientes Natural Language. Pour en savoir plus, consultez la documentation de référence de l'API Natural Language Go.

Pour vous authentifier auprès de Natural Language, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


func analyzeSyntax(ctx context.Context, client *language.Client, text string) (*languagepb.AnnotateTextResponse, error) {
	return client.AnnotateText(ctx, &languagepb.AnnotateTextRequest{
		Document: &languagepb.Document{
			Source: &languagepb.Document_Content{
				Content: text,
			},
			Type: languagepb.Document_PLAIN_TEXT,
		},
		Features: &languagepb.AnnotateTextRequest_Features{
			ExtractSyntax: true,
		},
		EncodingType: languagepb.EncodingType_UTF8,
	})
}

Java

Pour savoir comment installer et utiliser la bibliothèque cliente pour Natural Language, consultez la page Bibliothèques clientes Natural Language. Pour en savoir plus, consultez la documentation de référence de l'API Natural Language Java.

Pour vous authentifier auprès de Natural Language, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (com.google.cloud.language.v1.LanguageServiceClient language =
    com.google.cloud.language.v1.LanguageServiceClient.create()) {
  com.google.cloud.language.v1.Document doc =
      com.google.cloud.language.v1.Document.newBuilder().setContent(text)
        .setType(com.google.cloud.language.v1.Document.Type.PLAIN_TEXT).build();
  AnalyzeSyntaxRequest request =
      AnalyzeSyntaxRequest.newBuilder()
          .setDocument(doc)
          .setEncodingType(com.google.cloud.language.v1.EncodingType.UTF16)
          .build();
  // Analyze the syntax in the given text
  AnalyzeSyntaxResponse response = language.analyzeSyntax(request);
  // Print the response
  for (Token token : response.getTokensList()) {
    System.out.printf("\tText: %s\n", token.getText().getContent());
    System.out.printf("\tBeginOffset: %d\n", token.getText().getBeginOffset());
    System.out.printf("Lemma: %s\n", token.getLemma());
    System.out.printf("PartOfSpeechTag: %s\n", token.getPartOfSpeech().getTag());
    System.out.printf("\tAspect: %s\n", token.getPartOfSpeech().getAspect());
    System.out.printf("\tCase: %s\n", token.getPartOfSpeech().getCase());
    System.out.printf("\tForm: %s\n", token.getPartOfSpeech().getForm());
    System.out.printf("\tGender: %s\n", token.getPartOfSpeech().getGender());
    System.out.printf("\tMood: %s\n", token.getPartOfSpeech().getMood());
    System.out.printf("\tNumber: %s\n", token.getPartOfSpeech().getNumber());
    System.out.printf("\tPerson: %s\n", token.getPartOfSpeech().getPerson());
    System.out.printf("\tProper: %s\n", token.getPartOfSpeech().getProper());
    System.out.printf("\tReciprocity: %s\n", token.getPartOfSpeech().getReciprocity());
    System.out.printf("\tTense: %s\n", token.getPartOfSpeech().getTense());
    System.out.printf("\tVoice: %s\n", token.getPartOfSpeech().getVoice());
    System.out.println("DependencyEdge");
    System.out.printf("\tHeadTokenIndex: %d\n", token.getDependencyEdge().getHeadTokenIndex());
    System.out.printf("\tLabel: %s\n\n", token.getDependencyEdge().getLabel());
  }
  return response.getTokensList();
}

Node.js

Pour savoir comment installer et utiliser la bibliothèque cliente pour Natural Language, consultez la page Bibliothèques clientes Natural Language. Pour en savoir plus, consultez la documentation de référence de l'API Natural Language Node.js.

Pour vous authentifier auprès de Natural Language, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

// Need to specify an encodingType to receive word offsets
const encodingType = 'UTF8';

// Detects the sentiment of the document
const [syntax] = await client.analyzeSyntax({document, encodingType});

console.log('Tokens:');
syntax.tokens.forEach(part => {
  console.log(`${part.partOfSpeech.tag}: ${part.text.content}`);
  console.log('Morphology:', part.partOfSpeech);
});

Python

Pour savoir comment installer et utiliser la bibliothèque cliente pour Natural Language, consultez la page Bibliothèques clientes Natural Language. Pour en savoir plus, consultez la documentation de référence de l'API Natural Language Python.

Pour vous authentifier auprès de Natural Language, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

from google.cloud import language_v1

def sample_analyze_syntax(text_content):
    """
    Analyzing Syntax in a String

    Args:
      text_content The text content to analyze
    """

    client = language_v1.LanguageServiceClient()

    # text_content = 'This is a short sentence.'

    # 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:
    # https://cloud.google.com/natural-language/docs/languages
    language = "en"
    document = {"content": text_content, "type_": type_, "language": language}

    # Available values: NONE, UTF8, UTF16, UTF32
    encoding_type = language_v1.EncodingType.UTF8

    response = client.analyze_syntax(
        request={"document": document, "encoding_type": encoding_type}
    )
    # Loop through tokens returned from the API
    for token in response.tokens:
        # Get the text content of this token. Usually a word or punctuation.
        text = token.text
        print(f"Token text: {text.content}")
        print(f"Location of this token in overall document: {text.begin_offset}")
        # Get the part of speech information for this token.
        # Part of speech is defined in:
        # http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf
        part_of_speech = token.part_of_speech
        # Get the tag, e.g. NOUN, ADJ for Adjective, et al.
        print(
            "Part of Speech tag: {}".format(
                language_v1.PartOfSpeech.Tag(part_of_speech.tag).name
            )
        )
        # Get the voice, e.g. ACTIVE or PASSIVE
        print(
            "Voice: {}".format(
                language_v1.PartOfSpeech.Voice(part_of_speech.voice).name
            )
        )
        # Get the tense, e.g. PAST, FUTURE, PRESENT, et al.
        print(
            "Tense: {}".format(
                language_v1.PartOfSpeech.Tense(part_of_speech.tense).name
            )
        )
        # See API reference for additional Part of Speech information available
        # Get the lemma of the token. Wikipedia lemma description
        # https://en.wikipedia.org/wiki/Lemma_(morphology)
        print(f"Lemma: {token.lemma}")
        # Get the dependency tree parse information for this token.
        # For more information on dependency labels:
        # http://www.aclweb.org/anthology/P13-2017
        dependency_edge = token.dependency_edge
        print(f"Head token index: {dependency_edge.head_token_index}")
        print(
            "Label: {}".format(
                language_v1.DependencyEdge.Label(dependency_edge.label).name
            )
        )

    # 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}")

Langages supplémentaires

C# : Veuillez suivre les Instructions de configuration pour C# sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur Natural Language pour .NET.

PHP : Veuillez suivre les Instructions de configuration pour PHP sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur Natural Language pour PHP.

Ruby : Veuillez suivre les Instructions de configuration pour Ruby sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur Natural Language pour Ruby.

Analyser la syntaxe à partir de Cloud Storage

L'API Natural Language peut effectuer une analyse syntaxique directement sur un fichier situé dans Cloud Storage, ce qui se révèle plus pratique car il n'est pas nécessaire d'envoyer le contenu du fichier dans le corps de la requête.

Voici un exemple d'analyse syntaxique sur un fichier situé dans Cloud Storage.

Protocole

Pour analyser la syntaxe d'un document stocké dans Cloud Storage, envoyez une requête POST à la méthode REST documents:analyzeSyntax et fournissez un corps de requête approprié avec le chemin d'accès au document comme illustré dans l'exemple suivant.

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',
    'gcsContentUri': 'gs://<bucket-name>/<object-name>'
  }
}" "https://language.googleapis.com/v1/documents:analyzeSyntax"

Si vous ne spécifiez pas document.language, la langue est automatiquement détectée. Pour plus d'informations sur les langues acceptées par l'API Natural Language, consultez la page Langues acceptées. Pour en savoir plus sur la configuration du corps de la requête, reportez-vous à la documentation de référence sur Document.

Si la requête aboutit, le serveur renvoie un code d'état HTTP 200 OK et la réponse au format JSON :

{
  "sentences": [
    {
      "text": {
        "content": "Hello, world!",
        "beginOffset": 0
      }
    }
  ],
  "tokens": [
    {
      "text": {
        "content": "Hello",
        "beginOffset": 0
      },
      "partOfSpeech": {
        "tag": "X",
        // ...
      },
      "dependencyEdge": {
        "headTokenIndex": 2,
        "label": "DISCOURSE"
      },
      "lemma": "Hello"
    },
    {
      "text": {
        "content": ",",
        "beginOffset": 5
      },
      "partOfSpeech": {
        "tag": "PUNCT",
        // ...
      },
      "dependencyEdge": {
        "headTokenIndex": 2,
        "label": "P"
      },
      "lemma": ","
    },
    // ...
  ],
  "language": "en"
}

Le tableau tokens contient des objets Token représentant les jetons de phrases détectés, qui incluent des informations telles que la partie vocale du jeton et sa position dans la phrase.

gcloud

Reportez-vous à la commande analyze-syntax pour obtenir tous les détails.

Pour effectuer une analyse syntaxique sur un fichier dans Cloud Storage, utilisez l'outil de ligne de commande gcloud et utilisez l'indicateur --content-file pour identifier le chemin d'accès au contenu à analyser :

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

Si la requête aboutit, le serveur renvoie une réponse au format JSON :

{
  "sentences": [
    {
      "text": {
        "content": "Hello, world!",
        "beginOffset": 0
      }
    }
  ],
  "tokens": [
    {
      "text": {
        "content": "Hello",
        "beginOffset": 0
      },
      "partOfSpeech": {
        "tag": "X",
        // ...
      },
      "dependencyEdge": {
        "headTokenIndex": 2,
        "label": "DISCOURSE"
      },
      "lemma": "Hello"
    },
    {
      "text": {
        "content": ",",
        "beginOffset": 5
      },
      "partOfSpeech": {
        "tag": "PUNCT",
        // ...
      },
      "dependencyEdge": {
        "headTokenIndex": 2,
        "label": "P"
      },
      "lemma": ","
    },
    // ...
  ],
  "language": "en"
}

Le tableau tokens contient des objets Token représentant les jetons de phrases détectés, qui incluent des informations telles que la partie vocale du jeton et sa position dans la phrase.

Go

Pour savoir comment installer et utiliser la bibliothèque cliente pour Natural Language, consultez la page Bibliothèques clientes Natural Language. Pour en savoir plus, consultez la documentation de référence de l'API Natural Language Go.

Pour vous authentifier auprès de Natural Language, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


func analyzeSyntaxFromGCS(ctx context.Context, gcsURI string) (*languagepb.AnnotateTextResponse, error) {
	return client.AnnotateText(ctx, &languagepb.AnnotateTextRequest{
		Document: &languagepb.Document{
			Source: &languagepb.Document_GcsContentUri{
				GcsContentUri: gcsURI,
			},
			Type: languagepb.Document_PLAIN_TEXT,
		},
		Features: &languagepb.AnnotateTextRequest_Features{
			ExtractSyntax: true,
		},
		EncodingType: languagepb.EncodingType_UTF8,
	})
}

Java

Pour savoir comment installer et utiliser la bibliothèque cliente pour Natural Language, consultez la page Bibliothèques clientes Natural Language. Pour en savoir plus, consultez la documentation de référence de l'API Natural Language Java.

Pour vous authentifier auprès de Natural Language, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (com.google.cloud.language.v1.LanguageServiceClient language =
    com.google.cloud.language.v1.LanguageServiceClient.create()) {
  com.google.cloud.language.v1.Document doc =
      com.google.cloud.language.v1.Document.newBuilder().setGcsContentUri(gcsUri).setType(
        com.google.cloud.language.v1.Document.Type.PLAIN_TEXT
      ).build();
  AnalyzeSyntaxRequest request =
      AnalyzeSyntaxRequest.newBuilder()
          .setDocument(doc)
          .setEncodingType(com.google.cloud.language.v1.EncodingType.UTF16)
          .build();
  // Analyze the syntax in the given text
  AnalyzeSyntaxResponse response = language.analyzeSyntax(request);
  // Print the response
  for (Token token : response.getTokensList()) {
    System.out.printf("\tText: %s\n", token.getText().getContent());
    System.out.printf("\tBeginOffset: %d\n", token.getText().getBeginOffset());
    System.out.printf("Lemma: %s\n", token.getLemma());
    System.out.printf("PartOfSpeechTag: %s\n", token.getPartOfSpeech().getTag());
    System.out.printf("\tAspect: %s\n", token.getPartOfSpeech().getAspect());
    System.out.printf("\tCase: %s\n", token.getPartOfSpeech().getCase());
    System.out.printf("\tForm: %s\n", token.getPartOfSpeech().getForm());
    System.out.printf("\tGender: %s\n", token.getPartOfSpeech().getGender());
    System.out.printf("\tMood: %s\n", token.getPartOfSpeech().getMood());
    System.out.printf("\tNumber: %s\n", token.getPartOfSpeech().getNumber());
    System.out.printf("\tPerson: %s\n", token.getPartOfSpeech().getPerson());
    System.out.printf("\tProper: %s\n", token.getPartOfSpeech().getProper());
    System.out.printf("\tReciprocity: %s\n", token.getPartOfSpeech().getReciprocity());
    System.out.printf("\tTense: %s\n", token.getPartOfSpeech().getTense());
    System.out.printf("\tVoice: %s\n", token.getPartOfSpeech().getVoice());
    System.out.println("DependencyEdge");
    System.out.printf("\tHeadTokenIndex: %d\n", token.getDependencyEdge().getHeadTokenIndex());
    System.out.printf("\tLabel: %s\n\n", token.getDependencyEdge().getLabel());
  }

  return response.getTokensList();
}

Node.js

Pour savoir comment installer et utiliser la bibliothèque cliente pour Natural Language, consultez la page Bibliothèques clientes Natural Language. Pour en savoir plus, consultez la documentation de référence de l'API Natural Language Node.js.

Pour vous authentifier auprès de Natural Language, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

// Need to specify an encodingType to receive word offsets
const encodingType = 'UTF8';

// Detects the sentiment of the document
const [syntax] = await client.analyzeSyntax({document, encodingType});

console.log('Parts of speech:');
syntax.tokens.forEach(part => {
  console.log(`${part.partOfSpeech.tag}: ${part.text.content}`);
  console.log('Morphology:', part.partOfSpeech);
});

Python

Pour savoir comment installer et utiliser la bibliothèque cliente pour Natural Language, consultez la page Bibliothèques clientes Natural Language. Pour en savoir plus, consultez la documentation de référence de l'API Natural Language Python.

Pour vous authentifier auprès de Natural Language, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

from google.cloud import language_v1

def sample_analyze_syntax(gcs_content_uri):
    """
    Analyzing Syntax 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_v1.LanguageServiceClient()

    # gcs_content_uri = 'gs://cloud-samples-data/language/syntax-sentence.txt'

    # 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:
    # https://cloud.google.com/natural-language/docs/languages
    language = "en"
    document = {
        "gcs_content_uri": gcs_content_uri,
        "type_": type_,
        "language": language,
    }

    # Available values: NONE, UTF8, UTF16, UTF32
    encoding_type = language_v1.EncodingType.UTF8

    response = client.analyze_syntax(
        request={"document": document, "encoding_type": encoding_type}
    )
    # Loop through tokens returned from the API
    for token in response.tokens:
        # Get the text content of this token. Usually a word or punctuation.
        text = token.text
        print(f"Token text: {text.content}")
        print(f"Location of this token in overall document: {text.begin_offset}")
        # Get the part of speech information for this token.
        # Part of speech is defined in:
        # http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf
        part_of_speech = token.part_of_speech
        # Get the tag, e.g. NOUN, ADJ for Adjective, et al.
        print(
            "Part of Speech tag: {}".format(
                language_v1.PartOfSpeech.Tag(part_of_speech.tag).name
            )
        )
        # Get the voice, e.g. ACTIVE or PASSIVE
        print(
            "Voice: {}".format(
                language_v1.PartOfSpeech.Voice(part_of_speech.voice).name
            )
        )
        # Get the tense, e.g. PAST, FUTURE, PRESENT, et al.
        print(
            "Tense: {}".format(
                language_v1.PartOfSpeech.Tense(part_of_speech.tense).name
            )
        )
        # See API reference for additional Part of Speech information available
        # Get the lemma of the token. Wikipedia lemma description
        # https://en.wikipedia.org/wiki/Lemma_(morphology)
        print(f"Lemma: {token.lemma}")
        # Get the dependency tree parse information for this token.
        # For more information on dependency labels:
        # http://www.aclweb.org/anthology/P13-2017
        dependency_edge = token.dependency_edge
        print(f"Head token index: {dependency_edge.head_token_index}")
        print(
            "Label: {}".format(
                language_v1.DependencyEdge.Label(dependency_edge.label).name
            )
        )

    # 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}")

Langages supplémentaires

C# : Veuillez suivre les Instructions de configuration pour C# sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur Natural Language pour .NET.

PHP : Veuillez suivre les Instructions de configuration pour PHP sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur Natural Language pour PHP.

Ruby : Veuillez suivre les Instructions de configuration pour Ruby sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur Natural Language pour Ruby.