Azure Text Analytics-clientbibliotheek voor Python - versie 5.3.0

De Azure Cognitive Service for Language is een cloudservice die NLP-functies (Natural Language Processing) biedt voor het begrijpen en analyseren van tekst, en de volgende hoofdfuncties bevat:

  • Sentimentanalyse
  • Herkenning van benoemde entiteiten
  • Taaldetectie
  • Sleuteltermextractie
  • Entiteiten koppelen
  • Meervoudige analyse
  • Detectie van persoonsgegevens (PII)
  • Text Analytics voor de status
  • Aangepaste benoemde entiteitsherkenning
  • Aangepaste tekstclassificatie
  • Samenvatting van extractieve tekst
  • Samenvatting van abstracte tekst

Broncode | Pakket (PyPI) | Pakket (Conda) | API-referentiedocumentatie | Productdocumentatie | Monsters

Aan de slag

Vereisten

Een Cognitive Services- of Language-serviceresource maken

De Taalservice biedt ondersteuning voor toegang tot meerdere services en toegang tot één service. Maak een Cognitive Services-resource als u van plan bent toegang te krijgen tot meerdere Cognitive Services onder één eindpunt/sleutel. Maak een taalserviceresource voor alleen toegang tot taalservices. U kunt de resource maken met behulp van Azure Portal of Azure CLI door de stappen in dit document te volgen.

Interactie met de service met behulp van de clientbibliotheek begint met een . Als u een clientobject wilt maken, hebt u de Cognitive Services- of Language-service endpoint nodig voor uw resource en een credential waarmee u toegang krijgt tot:

from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

credential = AzureKeyCredential("<api_key>")
text_analytics_client = TextAnalyticsClient(endpoint="https://<resource-name>.cognitiveservices.azure.com/", credential=credential)

Houd er rekening mee dat voor sommige Cognitive Services-resources het eindpunt er anders uit kan zien dan het bovenstaande codefragment. Bijvoorbeeld https://<region>.api.cognitive.microsoft.com/.

Het pakket installeren

Installeer de Azure Text Analytics-clientbibliotheek voor Python met pip:

pip install azure-ai-textanalytics
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(endpoint, AzureKeyCredential(key))

Houd er rekening mee dat 5.2.X en nieuwer is gericht op de Azure Cognitive Service voor taal-API's. Deze API's bevatten de functies voor tekstanalyse en natuurlijke taalverwerking in de vorige versies van de Text Analytics-clientbibliotheek. Daarnaast is de service-API gewijzigd van semantische versiebeheer in versiebeheer op basis van datums. Deze versie van de clientbibliotheek is standaard ingesteld op de meest recente ondersteunde API-versie, die momenteel is 2023-04-01.

In deze tabel ziet u de relatie tussen SDK-versies en ondersteunde API-versies van de service

SDK-versie Ondersteunde API-versie van service
5.3.X - Meest recente stabiele release 3.0, 3.1, 2022-05-01, 2023-04-01 (standaard)
5.2.X 3.0, 3.1, 2022-05-01 (standaard)
5.1.0 3.0, 3.1 (standaard)
5.0.0 3,0

API-versie kan worden geselecteerd door het api_version sleutelwoordargument door te geven aan de client. Voor de nieuwste taalservicefuncties kunt u overwegen om de meest recente bèta-API-versie te selecteren. Voor productiescenario's wordt de meest recente stabiele versie aanbevolen. Instellen op een oudere versie kan leiden tot verminderde compatibiliteit van functies.

De client verifiëren

Het eindpunt ophalen

U kunt het eindpunt voor uw Taalserviceresource vinden met behulp van Azure Portal of Azure CLI:

# Get the endpoint for the Language service resource
az cognitiveservices account show --name "resource-name" --resource-group "resource-group-name" --query "properties.endpoint"

De API-sleutel ophalen

U kunt de API-sleutel ophalen uit de Cognitive Services- of Language-serviceresource in Azure Portal. U kunt ook het onderstaande Azure CLI-fragment gebruiken om de API-sleutel van uw resource op te halen.

az cognitiveservices account keys list --name "resource-name" --resource-group "resource-group-name"

Een TextAnalyticsClient maken met een API-sleutelreferentie

Zodra u de waarde voor de API-sleutel hebt, kunt u deze als een tekenreeks doorgeven aan een exemplaar van AzureKeyCredential. Gebruik de sleutel als referentieparameter om de client te verifiëren:

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(endpoint, AzureKeyCredential(key))

Een TextAnalyticsClient maken met een Azure Active Directory-referentie

Als u een AAD-tokenreferentie (Azure Active Directory) wilt gebruiken, geeft u een exemplaar op van het gewenste referentietype dat is verkregen uit de azure-identity-bibliotheek . Regionale eindpunten bieden geen ondersteuning voor AAD-verificatie. Maak een aangepaste subdomeinnaam voor uw resource om dit type verificatie te kunnen gebruiken.

Voor verificatie met AAD is enige initiële installatie vereist:

Na de installatie kunt u kiezen welk type referentie van azure.identity u wilt gebruiken. Als voorbeeld kan DefaultAzureCredential worden gebruikt om de client te verifiëren:

Stel de waarden van de client-id, tenant-id en clientgeheim van de AAD-toepassing in als omgevingsvariabelen: AZURE_CLIENT_ID, AZURE_TENANT_ID AZURE_CLIENT_SECRET

Gebruik de geretourneerde tokenreferentie om de client te verifiëren:

import os
from azure.ai.textanalytics import TextAnalyticsClient
from azure.identity import DefaultAzureCredential

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
credential = DefaultAzureCredential()

text_analytics_client = TextAnalyticsClient(endpoint, credential=credential)

Belangrijkste concepten

TextAnalyticsClient

De Text Analytics-clientbibliotheek biedt een TextAnalyticsClient om analyse uit te voeren op van batches van documenten. Het biedt zowel synchrone als asynchrone bewerkingen voor toegang tot een specifiek gebruik van tekstanalyse, zoals taaldetectie of sleuteltermextractie.

Invoer

Een document is één eenheid die moet worden geanalyseerd door de voorspellende modellen in de Taalservice. De invoer voor elke bewerking wordt doorgegeven als een lijst met documenten.

Elk document kan worden doorgegeven als een tekenreeks in de lijst, bijvoorbeeld

documents = ["I hated the movie. It was so slow!", "The movie made it into my top ten favorites. What a great movie!"]

of, als u een document id per item of languagecountry_hint/wilt doorgeven, kunnen deze worden doorgegeven als een lijst met DetectLanguageInput of TextDocumentInput of een dict-achtige weergave van het object:

documents = [
    {"id": "1", "language": "en", "text": "I hated the movie. It was so slow!"},
    {"id": "2", "language": "en", "text": "The movie made it into my top ten favorites. What a great movie!"},
]

Zie servicebeperkingen voor de invoer, waaronder limieten voor documentlengte, maximale batchgrootte en ondersteunde tekstcodering.

Retourwaarde

De geretourneerde waarde voor één document kan een resultaat- of foutobject zijn. Een heterogene lijst met een verzameling resultaat- en foutobjecten wordt geretourneerd van elke bewerking. Deze resultaten/fouten worden geïndexeerd met de volgorde van de opgegeven documenten.

Een resultaat, zoals AnalyzeSentimentResult, is het resultaat van een tekstanalysebewerking en bevat een voorspelling of voorspellingen over een documentinvoer.

Het foutobject, DocumentError, geeft aan dat de service problemen had met het verwerken van het document en bevat de reden waarom het niet lukte.

Afhandeling van documentfouten

U kunt filteren op een resultaat- of foutobject in de lijst met behulp van het is_error kenmerk . Voor een resultaatobject is dit altijd False en voor een DocumentError is Truedit .

Als u bijvoorbeeld alle DocumentErrors wilt uitfilteren, kunt u lijstbegrip gebruiken:

response = text_analytics_client.analyze_sentiment(documents)
successful_responses = [doc for doc in response if not doc.is_error]

U kunt het kind kenmerk ook gebruiken om te filteren tussen resultaattypen:

poller = text_analytics_client.begin_analyze_actions(documents, actions)
response = poller.result()
for result in response:
    if result.kind == "SentimentAnalysis":
        print(f"Sentiment is {result.sentiment}")
    elif result.kind == "KeyPhraseExtraction":
        print(f"Key phrases: {result.key_phrases}")
    elif result.is_error is True:
        print(f"Document error: {result.code}, {result.message}")

Long-Running bewerkingen

Langlopende bewerkingen zijn bewerkingen die bestaan uit een eerste aanvraag die naar de service wordt verzonden om een bewerking te starten, gevolgd door het pollen van de service met intervallen om te bepalen of de bewerking is voltooid of mislukt, en of deze is geslaagd, om het resultaat op te halen.

Methoden die ondersteuning bieden voor gezondheidszorganalyse, aangepaste tekstanalyse of meerdere analyses, worden gemodelleerd als langdurige bewerkingen. De client maakt een begin_<method-name> methode beschikbaar die een poller-object retourneert. Aanroepende gebruikers moeten wachten tot de bewerking is voltooid door het poller-object aan te roepen result() dat door de begin_<method-name> methode is geretourneerd. Voorbeeldcodefragmenten worden verstrekt ter illustratie van langlopende bewerkingen hieronder.

Voorbeelden

De volgende sectie bevat verschillende codefragmenten voor enkele van de meest voorkomende taalservicetaken, waaronder:

Sentiment analyseren

analyze_sentiment bekijkt de invoertekst en bepaalt of het gevoel positief, negatief, neutraal of gemengd is. Het antwoord omvat sentimentanalyse per zin en betrouwbaarheidsscores.

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))

documents = [
    """I had the best day of my life. I decided to go sky-diving and it made me appreciate my whole life so much more.
    I developed a deep-connection with my instructor as well, and I feel as if I've made a life-long friend in her.""",
    """This was a waste of my time. All of the views on this drop are extremely boring, all I saw was grass. 0/10 would
    not recommend to any divers, even first timers.""",
    """This was pretty good! The sights were ok, and I had fun with my instructors! Can't complain too much about my experience""",
    """I only have one word for my experience: WOW!!! I can't believe I have had such a wonderful skydiving company right
    in my backyard this whole time! I will definitely be a repeat customer, and I want to take my grandmother skydiving too,
    I know she'll love it!"""
]


result = text_analytics_client.analyze_sentiment(documents, show_opinion_mining=True)
docs = [doc for doc in result if not doc.is_error]

print("Let's visualize the sentiment of each of these documents")
for idx, doc in enumerate(docs):
    print(f"Document text: {documents[idx]}")
    print(f"Overall sentiment: {doc.sentiment}")

Het geretourneerde antwoord is een heterogene lijst met resultaat- en foutobjecten: list[AnalyzeSentimentResult, DocumentError]

Raadpleeg de servicedocumentatie voor een conceptuele bespreking van sentimentanalyse. Zie hier voor meer informatie over het uitvoeren van een gedetailleerde analyse van de meningen met betrekking tot afzonderlijke aspecten (zoals kenmerken van een product of service) in een tekst.

Entiteiten herkennen

recognize_entities herkent entiteiten en categorieën in de invoertekst als personen, plaatsen, organisaties, datum/tijd, hoeveelheden, percentages, valuta's en meer.

import os
import typing
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
reviews = [
    """I work for Foo Company, and we hired Contoso for our annual founding ceremony. The food
    was amazing and we all can't say enough good words about the quality and the level of service.""",
    """We at the Foo Company re-hired Contoso after all of our past successes with the company.
    Though the food was still great, I feel there has been a quality drop since their last time
    catering for us. Is anyone else running into the same problem?""",
    """Bar Company is over the moon about the service we received from Contoso, the best sliders ever!!!!"""
]

result = text_analytics_client.recognize_entities(reviews)
result = [review for review in result if not review.is_error]
organization_to_reviews: typing.Dict[str, typing.List[str]] = {}

for idx, review in enumerate(result):
    for entity in review.entities:
        print(f"Entity '{entity.text}' has category '{entity.category}'")
        if entity.category == 'Organization':
            organization_to_reviews.setdefault(entity.text, [])
            organization_to_reviews[entity.text].append(reviews[idx])

for organization, reviews in organization_to_reviews.items():
    print(
        "\n\nOrganization '{}' has left us the following review(s): {}".format(
            organization, "\n\n".join(reviews)
        )
    )

Het geretourneerde antwoord is een heterogene lijst met resultaat- en foutobjecten: list[RecognizeEntitiesResult, DocumentError]

Raadpleeg de servicedocumentatie voor een conceptuele bespreking van benoemde entiteitsherkenning en ondersteunde typen.

Gekoppelde entiteiten herkennen

recognize_linked_entities herkent en ondubbelzinnig de identiteit van elke entiteit die wordt gevonden in de invoertekst (bijvoorbeeld om te bepalen of een voorval van het woord Mars verwijst naar de planeet of naar de Romeinse god van de oorlog). Herkende entiteiten zijn gekoppeld aan URL's naar een bekende Knowledge Base, zoals Wikipedia.

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
documents = [
    """
    Microsoft was founded by Bill Gates with some friends he met at Harvard. One of his friends,
    Steve Ballmer, eventually became CEO after Bill Gates as well. Steve Ballmer eventually stepped
    down as CEO of Microsoft, and was succeeded by Satya Nadella.
    Microsoft originally moved its headquarters to Bellevue, Washington in January 1979, but is now
    headquartered in Redmond.
    """
]

result = text_analytics_client.recognize_linked_entities(documents)
docs = [doc for doc in result if not doc.is_error]

print(
    "Let's map each entity to it's Wikipedia article. I also want to see how many times each "
    "entity is mentioned in a document\n\n"
)
entity_to_url = {}
for doc in docs:
    for entity in doc.entities:
        print("Entity '{}' has been mentioned '{}' time(s)".format(
            entity.name, len(entity.matches)
        ))
        if entity.data_source == "Wikipedia":
            entity_to_url[entity.name] = entity.url

Het geretourneerde antwoord is een heterogene lijst met resultaat- en foutobjecten: list[RecognizeLinkedEntitiesResult, DocumentError]

Raadpleeg de servicedocumentatie voor een conceptuele bespreking van entiteitskoppeling en ondersteunde typen.

PII-entiteiten herkennen

recognize_pii_entities herkent en categoriseert entiteiten met persoonlijke gegevens (PII) in de invoertekst, zoals burgerservicenummers, bankrekeninggegevens, creditcardnummers en meer.

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(
    endpoint=endpoint, credential=AzureKeyCredential(key)
)
documents = [
    """Parker Doe has repaid all of their loans as of 2020-04-25.
    Their SSN is 859-98-0987. To contact them, use their phone number
    555-555-5555. They are originally from Brazil and have Brazilian CPF number 998.214.865-68"""
]

result = text_analytics_client.recognize_pii_entities(documents)
docs = [doc for doc in result if not doc.is_error]

print(
    "Let's compare the original document with the documents after redaction. "
    "I also want to comb through all of the entities that got redacted"
)
for idx, doc in enumerate(docs):
    print(f"Document text: {documents[idx]}")
    print(f"Redacted document text: {doc.redacted_text}")
    for entity in doc.entities:
        print("...Entity '{}' with category '{}' got redacted".format(
            entity.text, entity.category
        ))

Het geretourneerde antwoord is een heterogene lijst met resultaat- en foutobjecten: list[RecognizePiiEntitiesResult, DocumentError]

Raadpleeg de servicedocumentatie voor ondersteunde PII-entiteitstypen.

Opmerking: de service Recognize PII Entities is beschikbaar in API-versie v3.1 en hoger.

Sleuteltermen ophalen

extract_key_phrases bepaalt de belangrijkste gesprekspunten in de invoertekst. Voor de invoertekst 'Het eten was heerlijk en er was geweldig personeel', retourneert de API bijvoorbeeld: 'eten' en 'geweldig personeel'.

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
articles = [
    """
    Washington, D.C. Autumn in DC is a uniquely beautiful season. The leaves fall from the trees
    in a city chock-full of forests, leaving yellow leaves on the ground and a clearer view of the
    blue sky above...
    """,
    """
    Redmond, WA. In the past few days, Microsoft has decided to further postpone the start date of
    its United States workers, due to the pandemic that rages with no end in sight...
    """,
    """
    Redmond, WA. Employees at Microsoft can be excited about the new coffee shop that will open on campus
    once workers no longer have to work remotely...
    """
]

result = text_analytics_client.extract_key_phrases(articles)
for idx, doc in enumerate(result):
    if not doc.is_error:
        print("Key phrases in article #{}: {}".format(
            idx + 1,
            ", ".join(doc.key_phrases)
        ))

Het geretourneerde antwoord is een heterogene lijst met resultaat- en foutobjecten: list[ExtractKeyPhrasesResult, DocumentError]

Raadpleeg de servicedocumentatie voor een conceptuele bespreking van sleuteltermextractie.

Taal detecteren

detect_language bepaalt de taal van de invoertekst, inclusief de betrouwbaarheidsscore van de voorspelde taal.

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
documents = [
    """
    The concierge Paulette was extremely helpful. Sadly when we arrived the elevator was broken, but with Paulette's help we barely noticed this inconvenience.
    She arranged for our baggage to be brought up to our room with no extra charge and gave us a free meal to refurbish all of the calories we lost from
    walking up the stairs :). Can't say enough good things about my experience!
    """,
    """
    最近由于工作压力太大,我们决定去富酒店度假。那儿的温泉实在太舒服了,我跟我丈夫都完全恢复了工作前的青春精神!加油!
    """
]

result = text_analytics_client.detect_language(documents)
reviewed_docs = [doc for doc in result if not doc.is_error]

print("Let's see what language each review is in!")

for idx, doc in enumerate(reviewed_docs):
    print("Review #{} is in '{}', which has ISO639-1 name '{}'\n".format(
        idx, doc.primary_language.name, doc.primary_language.iso6391_name
    ))

Het geretourneerde antwoord is een heterogene lijst met resultaat- en foutobjecten: list[DetectLanguageResult, DocumentError]

Raadpleeg de servicedocumentatie voor een conceptuele bespreking van taaldetectie en taal- en regionale ondersteuning.

Analyse van gezondheidszorgentiteiten

Langdurige bewerkingbegin_analyze_healthcare_entities haalt entiteiten op die worden herkend binnen het gezondheidszorgdomein en identificeert relaties tussen entiteiten in het invoerdocument en koppelingen naar bekende informatiebronnen in verschillende bekende databases, zoals UMLS, CHV, MSH, enzovoort.

import os
import typing
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient, HealthcareEntityRelation

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(
    endpoint=endpoint,
    credential=AzureKeyCredential(key),
)

documents = [
    """
    Patient needs to take 100 mg of ibuprofen, and 3 mg of potassium. Also needs to take
    10 mg of Zocor.
    """,
    """
    Patient needs to take 50 mg of ibuprofen, and 2 mg of Coumadin.
    """
]

poller = text_analytics_client.begin_analyze_healthcare_entities(documents)
result = poller.result()

docs = [doc for doc in result if not doc.is_error]

print("Let's first visualize the outputted healthcare result:")
for doc in docs:
    for entity in doc.entities:
        print(f"Entity: {entity.text}")
        print(f"...Normalized Text: {entity.normalized_text}")
        print(f"...Category: {entity.category}")
        print(f"...Subcategory: {entity.subcategory}")
        print(f"...Offset: {entity.offset}")
        print(f"...Confidence score: {entity.confidence_score}")
        if entity.data_sources is not None:
            print("...Data Sources:")
            for data_source in entity.data_sources:
                print(f"......Entity ID: {data_source.entity_id}")
                print(f"......Name: {data_source.name}")
        if entity.assertion is not None:
            print("...Assertion:")
            print(f"......Conditionality: {entity.assertion.conditionality}")
            print(f"......Certainty: {entity.assertion.certainty}")
            print(f"......Association: {entity.assertion.association}")
    for relation in doc.entity_relations:
        print(f"Relation of type: {relation.relation_type} has the following roles")
        for role in relation.roles:
            print(f"...Role '{role.name}' with entity '{role.entity.text}'")
    print("------------------------------------------")

print("Now, let's get all of medication dosage relations from the documents")
dosage_of_medication_relations = [
    entity_relation
    for doc in docs
    for entity_relation in doc.entity_relations if entity_relation.relation_type == HealthcareEntityRelation.DOSAGE_OF_MEDICATION
]

Opmerking: Healthcare Entities Analysis is alleen beschikbaar met API-versie v3.1 en hoger.

Meervoudige analyse

Langdurige bewerkingbegin_analyze_actions voert meerdere analyses uit op één set documenten in één aanvraag. Momenteel wordt het ondersteund met behulp van een combinatie van de volgende taal-API's in één aanvraag:

  • Herkenning van entiteiten
  • Herkenning van PII-entiteiten
  • Herkenning van gekoppelde entiteiten
  • Sleuteltermextractie
  • Sentimentanalyse
  • Aangepaste entiteitsherkenning (API-versie 2022-05-01 en hoger)
  • Aangepaste classificatie van één label (API-versie 2022-05-01 en hoger)
  • Aangepaste classificatie van meerdere labels (API-versie 2022-05-01 en hoger)
  • Healthcare Entities Analysis (API-versie 2022-05-01 en hoger)
  • Extractieve samenvatting (API-versie 2023-04-01 en hoger)
  • Abstractieve samenvatting (API-versie 2023-04-01 en hoger)
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import (
    TextAnalyticsClient,
    RecognizeEntitiesAction,
    RecognizeLinkedEntitiesAction,
    RecognizePiiEntitiesAction,
    ExtractKeyPhrasesAction,
    AnalyzeSentimentAction,
)

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(
    endpoint=endpoint,
    credential=AzureKeyCredential(key),
)

documents = [
    'We went to Contoso Steakhouse located at midtown NYC last week for a dinner party, and we adore the spot! '
    'They provide marvelous food and they have a great menu. The chief cook happens to be the owner (I think his name is John Doe) '
    'and he is super nice, coming out of the kitchen and greeted us all.'
    ,

    'We enjoyed very much dining in the place! '
    'The Sirloin steak I ordered was tender and juicy, and the place was impeccably clean. You can even pre-order from their '
    'online menu at www.contososteakhouse.com, call 312-555-0176 or send email to order@contososteakhouse.com! '
    'The only complaint I have is the food didn\'t come fast enough. Overall I highly recommend it!'
]

poller = text_analytics_client.begin_analyze_actions(
    documents,
    display_name="Sample Text Analysis",
    actions=[
        RecognizeEntitiesAction(),
        RecognizePiiEntitiesAction(),
        ExtractKeyPhrasesAction(),
        RecognizeLinkedEntitiesAction(),
        AnalyzeSentimentAction(),
    ],
)

document_results = poller.result()
for doc, action_results in zip(documents, document_results):
    print(f"\nDocument text: {doc}")
    for result in action_results:
        if result.kind == "EntityRecognition":
            print("...Results of Recognize Entities Action:")
            for entity in result.entities:
                print(f"......Entity: {entity.text}")
                print(f".........Category: {entity.category}")
                print(f".........Confidence Score: {entity.confidence_score}")
                print(f".........Offset: {entity.offset}")

        elif result.kind == "PiiEntityRecognition":
            print("...Results of Recognize PII Entities action:")
            for pii_entity in result.entities:
                print(f"......Entity: {pii_entity.text}")
                print(f".........Category: {pii_entity.category}")
                print(f".........Confidence Score: {pii_entity.confidence_score}")

        elif result.kind == "KeyPhraseExtraction":
            print("...Results of Extract Key Phrases action:")
            print(f"......Key Phrases: {result.key_phrases}")

        elif result.kind == "EntityLinking":
            print("...Results of Recognize Linked Entities action:")
            for linked_entity in result.entities:
                print(f"......Entity name: {linked_entity.name}")
                print(f".........Data source: {linked_entity.data_source}")
                print(f".........Data source language: {linked_entity.language}")
                print(
                    f".........Data source entity ID: {linked_entity.data_source_entity_id}"
                )
                print(f".........Data source URL: {linked_entity.url}")
                print(".........Document matches:")
                for match in linked_entity.matches:
                    print(f"............Match text: {match.text}")
                    print(f"............Confidence Score: {match.confidence_score}")
                    print(f"............Offset: {match.offset}")
                    print(f"............Length: {match.length}")

        elif result.kind == "SentimentAnalysis":
            print("...Results of Analyze Sentiment action:")
            print(f"......Overall sentiment: {result.sentiment}")
            print(
                f"......Scores: positive={result.confidence_scores.positive}; \
                neutral={result.confidence_scores.neutral}; \
                negative={result.confidence_scores.negative} \n"
            )

        elif result.is_error is True:
            print(
                f"...Is an error with code '{result.error.code}' and message '{result.error.message}'"
            )

    print("------------------------------------------")

Het geretourneerde antwoord is een object dat meerdere iterables inkapselt, die elk de resultaten van afzonderlijke analyses vertegenwoordigen.

Opmerking: Meervoudige analyse is beschikbaar in API-versie v3.1 en hoger.

Optionele configuratie

Optionele trefwoordargumenten kunnen worden doorgegeven op het niveau van de client en per bewerking. In de naslagdocumentatie van Azure Core worden de beschikbare configuraties beschreven voor nieuwe pogingen, logboekregistratie, transportprotocollen en meer.

Problemen oplossen

Algemeen

De Text Analytics-client genereert uitzonderingen die zijn gedefinieerd in Azure Core.

Logboekregistratie

Deze bibliotheek maakt gebruik van de standaardbibliotheek voor logboekregistratie voor logboekregistratie. Basisinformatie over HTTP-sessies (URL's, headers, enzovoort) wordt geregistreerd op INFO-niveau.

Gedetailleerde logboekregistratie op DEBUG-niveau met aanvraag/antwoord-body's en niet-geredigeerde headers, kan worden ingeschakeld op een client met het sleutelwoordargument logging_enable:

import sys
import logging
from azure.identity import DefaultAzureCredential
from azure.ai.textanalytics import TextAnalyticsClient

# Create a logger for the 'azure' SDK
logger = logging.getLogger('azure')
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

endpoint = "https://<resource-name>.cognitiveservices.azure.com/"
credential = DefaultAzureCredential()

# This client will log detailed information about its HTTP sessions, at DEBUG level
text_analytics_client = TextAnalyticsClient(endpoint, credential, logging_enable=True)
result = text_analytics_client.analyze_sentiment(["I did not like the restaurant. The food was too spicy."])

Op dezelfde manier kan logging_enable logboekregistratie voor één bewerking inschakelen, zelfs wanneer dit niet is ingeschakeld voor de client:

result = text_analytics_client.analyze_sentiment(documents, logging_enable=True)

Volgende stappen

Meer voorbeeldcode

Deze codevoorbeelden tonen algemene scenariobewerkingen met de Azure Text Analytics-clientbibliotheek.

Verifieer de client met een Api-sleutel voor de Cognitive Services/Language-service of een tokenreferentie van azure-identity:

Algemene scenario's

Geavanceerde scenario's

Aanvullende documentatie

Zie de Documentatie voor Taalservice op docs.microsoft.com voor uitgebreidere documentatie over Azure Cognitive Service for Language.

Bijdragen

Wij verwelkomen bijdragen en suggesties voor dit project. Voor de meeste bijdragen moet u instemmen met een licentieovereenkomst voor bijdragers (CLA: Contributor License Agreement) waarin u verklaart dat u gerechtigd bent ons het recht te geven uw bijdrage te gebruiken, en dat u dit ook doet. Ga naar cla.microsoft.com voor meer informatie.

Wanneer u een pull-aanvraag indient, wordt met een CLA-bot automatisch bepaald of u een CLA moet verschaffen en wordt de pull-aanvraag dienovereenkomstig opgemaakt (bijvoorbeeld met een label of commentaar). Volg gewoon de instructies van de bot. U hoeft dit maar eenmaal te doen voor alle repo's waar gebruik wordt gemaakt van onze CLA.

Op dit project is de Microsoft Open Source Code of Conduct (Microsoft Open Source-gedragscode) van toepassing. Zie de Veelgestelde vragen over de gedragscode voor meer informatie of neem contact op opencode@microsoft.com met eventuele aanvullende vragen of opmerkingen.