关于 azure-ai-textanalytics-py
面向开发者的 Azure AI Language 文本分析 Python 客户端库,可将 NLP 分析集成到应用中。提供同步和异步 API,用于情感、实体、个人信息、关键词、语言及医疗文本分析。
主要功能
- 01分析情感与观点
- 02识别并关联实体
- 03检测并遮盖个人信息
- 04提取关键词并检测语言
- 05分析医疗文本和批次
- 06使用同步或异步客户端
适用场景
- 01判断客户反馈的情感倾向
- 02从文档提取实体和关键词
- 03检测并遮盖个人信息
- 04批量识别文本语言
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ sickn33/ agentic-awesome-skills --skill azure-ai-textanalytics-py安装后在 Claude Code 中输入/azure-ai-textanalytics-py确认已加载。
详细介绍
Azure AI Text Analytics SDK for Python
用于 Azure AI Language 服务 NLP 功能的客户端库,包括情感、实体、关键短语等。
安装
pip install azure-ai-textanalytics
环境变量
AZURE_LANGUAGE_ENDPOINT=https://<resource>.cognitiveservices.azure.com
AZURE_LANGUAGE_KEY=<your-api-key> # If using API key
身份验证
API 密钥
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"]
client = TextAnalyticsClient(endpoint, AzureKeyCredential(key))
Entra ID(推荐)
from azure.ai.textanalytics import TextAnalyticsClient
from azure.identity import DefaultAzureCredential
client = TextAnalyticsClient(
endpoint=os.environ["AZURE_LANGUAGE_ENDPOINT"],
credential=DefaultAzureCredential()
)
数据处理
调用会将文档文本发送到 Azure。对于私人、PII 或健康数据,请先取得授权,并核实区域、保留期限和允许的用途;脱敏结果具有概率性,无法保证实现去标识化。医疗信息提取不等同于诊断。各示例均为独立片段;使用结果字段前,请检查每个文档是否出错。
情感分析
documents = [
"I had a wonderful trip to Seattle last week!",
"The food was terrible and the service was slow."
]
result = client.analyze_sentiment(documents, show_opinion_mining=True)
for doc in result:
if not doc.is_error:
print(f"Sentiment: {doc.sentiment}")
print(f"Scores: pos={doc.confidence_scores.positive:.2f}, "
f"neg={doc.confidence_scores.negative:.2f}, "
f"neu={doc.confidence_scores.neutral:.2f}")
# Opinion mining (aspect-based sentiment)
for sentence in doc.sentences:
for opinion in sentence.mined_opinions:
target = opinion.target
print(f" Target: '{target.text}' - {target.sentiment}")
for assessment in opinion.assessments:
print(f" Assessment: '{assessment.text}' - {assessment.sentiment}")
实体识别
documents = ["Microsoft was founded by Bill Gates and Paul Allen in Albuquerque."]
result = client.recognize_entities(documents)
for doc in result:
if not doc.is_error:
for entity in doc.entities:
print(f"Entity: {entity.text}")
print(f" Category: {entity.category}")
print(f" Subcategory: {entity.subcategory}")
print(f" Confidence: {entity.confidence_score:.2f}")
PII 检测
documents = ["My SSN is 123-45-6789 and my email is [email protected]"]
result = client.recognize_pii_entities(documents)
for doc in result:
if not doc.is_error:
print(f"Redacted: {doc.redacted_text}")
for entity in doc.entities:
print(f"PII category: {entity.category}") # Do not log detected sensitive values.
关键短语提取
documents = ["Azure AI provides powerful machine learning capabilities for developers."]
result = client.extract_key_phrases(documents)
for doc in result:
if not doc.is_error:
print(f"Key phrases: {doc.key_phrases}")
语言检测
documents = ["Ce document est en francais.", "This is written in English."]
result = client.detect_language(documents)
for doc in result:
if not doc.is_error:
print(f"Language: {doc.primary_language.name} ({doc.primary_language.iso6391_name})")
print(f"Confidence: {doc.primary_language.confidence_score:.2f}")
医疗文本分析
documents = ["Patient has diabetes and was prescribed metformin 500mg twice daily."]
poller = client.begin_analyze_healthcare_entities(documents)
result = poller.result()
for doc in result:
if not doc.is_error:
for entity in doc.entities:
print(f"Entity: {entity.text}")
print(f" Category: {entity.category}")
print(f" Normalized: {entity.normalized_text}")
# Entity links (UMLS, etc.)
for link in entity.data_sources:
print(f" Link: {link.name} - {link.entity_id}")
多项分析(批处理)
from azure.ai.textanalytics import (
RecognizeEntitiesAction,
ExtractKeyPhrasesAction,
AnalyzeSentimentAction
)
documents = ["Microsoft announced new Azure AI features at Build conference."]
poller = client.begin_analyze_actions(
documents,
actions=[
RecognizeEntitiesAction(),
ExtractKeyPhrasesAction(),
AnalyzeSentimentAction()
]
)
results = poller.result()
for doc_results in results:
for result in doc_results:
if result.kind == "EntityRecognition":
print(f"Entities: {[e.text for e in result.entities]}")
elif result.kind == "KeyPhraseExtraction":
print(f"Key phrases: {result.key_phrases}")
elif result.kind == "SentimentAnalysis":
print(f"Sentiment: {result.sentiment}")
异步客户端
from azure.ai.textanalytics.aio import TextAnalyticsClient
from azure.identity.aio import DefaultAzureCredential
async def analyze():
async with TextAnalyticsClient(
endpoint=endpoint,
credential=DefaultAzureCredential()
) as client:
result = await client.analyze_sentiment(documents)
# Process results...
客户端类型
| 客户端 | 用途 |
|---|---|
TextAnalyticsClient | 所有文本分析操作 |
TextAnalyticsClient (aio) | 异步版本 |
可用操作
| 方法 | 描述 |
|---|---|
analyze_sentiment | 带观点挖掘的情感分析 |
recognize_entities | 命名实体识别 |
recognize_pii_entities | PII 检测与脱敏 |
recognize_linked_entities | 将实体链接到 Wikipedia |
extract_key_phrases | 关键短语提取 |
detect_language | 语言检测 |
begin_analyze_healthcare_entities | 医疗 NLP(长时间运行) |
begin_analyze_actions | 批量执行多项分析 |
最佳实践
- 使用批处理操作处理多个文档(每个请求最多 10 个)
- 启用观点挖掘,以进行详细的方面级情感分析
- 在高吞吐量场景中使用异步客户端
- 处理文档错误——结果列表中的某些文档可能包含错误
- 已知语言时指定语言,以提高准确性
- 使用上下文管理器或显式关闭客户端
适用场景
当任务与概述中描述的工作流或操作相符时,可使用此技能。
限制
- 仅当任务明确符合上述范围时,才使用此技能。
- 不要将输出视为环境特定验证、测试或专家审查的替代品。
- 如果缺少必要输入、权限、安全边界或成功标准,请暂停并请求澄清。
评论
支持 Markdown