Comprehend Basics
Seven examples to get you started with Amazon Comprehend - five basic and two intermediate.
Busca en todas las páginas de la documentación
Seven examples to get you started with Amazon Comprehend - five basic and two intermediate.
Each example shows the same operation in both Python (boto3) and TypeScript (AWS SDK for JavaScript v3).
pip install boto3 (boto3 1.43.x, Python 3.10+). TypeScript: npm install @aws-sdk/client-comprehend (Node.js 18+).aws configure, environment variables, or an IAM role. The SDK finds them automatically.us-east-1.The starting point for every call is a service client bound to a region.
# --- Python (boto3) ---
import boto3
comprehend = boto3.client("comprehend", region_name="us-east-1")
print(type(comprehend)) # <class 'botocore.client.Comprehend'>// --- TypeScript (AWS SDK v3) ---
import { ComprehendClient } from "@aws-sdk/client-comprehend";
const comprehend = new ComprehendClient({ region: "us-east-1" });
console.log(comprehend.constructor.name); // ComprehendClientRelated: Comprehend's Managed NLP Model Surface - the pretrained vs custom, real-time vs batch map.
DetectSentiment classifies a block of text as Positive, Negative, Neutral, or Mixed, with a confidence score for each.
# --- Python (boto3) ---
import boto3
comprehend = boto3.client("comprehend")
resp = comprehend.detect_sentiment(
Text="Shipping was fast but the packaging was damaged.",
LanguageCode="en",
)
print(resp["Sentiment"]) # e.g. MIXED
print(resp["SentimentScore"]) # {'Positive': .., 'Negative': .., 'Neutral': .., 'Mixed': ..}// --- TypeScript (AWS SDK v3) ---
import { ComprehendClient, DetectSentimentCommand } from "@aws-sdk/client-comprehend";
const comprehend = new ComprehendClient({});
const resp = await comprehend.send(new DetectSentimentCommand({
Text: "Shipping was fast but the packaging was damaged.",
LanguageCode: "en",
}));
console.log(resp.Sentiment); // e.g. MIXED
console.log(resp.SentimentScore); // { Positive, Negative, Neutral, Mixed }Sentiment is one of POSITIVE, NEGATIVE, NEUTRAL, or MIXED.SentimentScore gives a confidence value for all four labels, not just the winning one.LanguageCode is required; it tells Comprehend which language model to apply.DetectDominantLanguage identifies what language a piece of text is written in, ranked by confidence.
# --- Python (boto3) ---
import boto3
comprehend = boto3.client("comprehend")
resp = comprehend.detect_dominant_language(
Text="Merci pour votre reponse rapide.",
)
for lang in resp["Languages"]:
print(lang["LanguageCode"], lang["Score"])// --- TypeScript (AWS SDK v3) ---
import { ComprehendClient, DetectDominantLanguageCommand } from "@aws-sdk/client-comprehend";
const comprehend = new ComprehendClient({});
const resp = await comprehend.send(new DetectDominantLanguageCommand({
Text: "Merci pour votre reponse rapide.",
}));
for (const lang of resp.Languages ?? []) {
console.log(lang.LanguageCode, lang.Score);
}LanguageCode input - detecting it is the point.Languages can list more than one candidate for mixed-language text, sorted by score.DetectEntities finds named things in text - people, places, organizations, dates, and more - with their location in the string.
# --- Python (boto3) ---
import boto3
comprehend = boto3.client("comprehend")
resp = comprehend.detect_entities(
Text="Maria Gomez visited the Seattle office on March 3rd.",
LanguageCode="en",
)
for entity in resp["Entities"]:
print(entity["Type"], entity["Text"], entity["Score"])// --- TypeScript (AWS SDK v3) ---
import { ComprehendClient, DetectEntitiesCommand } from "@aws-sdk/client-comprehend";
const comprehend = new ComprehendClient({});
const resp = await comprehend.send(new DetectEntitiesCommand({
Text: "Maria Gomez visited the Seattle office on March 3rd.",
LanguageCode: "en",
}));
for (const entity of resp.Entities ?? []) {
console.log(entity.Type, entity.Text, entity.Score);
}Type values include PERSON, LOCATION, ORGANIZATION, DATE, QUANTITY, and more.BeginOffset/EndOffset, the exact character span in your input text.Score is a 0-1 confidence value; filter low-confidence matches for stricter pipelines.DetectKeyPhrases pulls out the noun phrases that carry the most meaning in a passage, without needing a full parse.
# --- Python (boto3) ---
import boto3
comprehend = boto3.client("comprehend")
resp = comprehend.detect_key_phrases(
Text="The quarterly earnings report exceeded analyst expectations.",
LanguageCode="en",
)
for phrase in resp["KeyPhrases"]:
print(phrase["Text"], phrase["Score"])// --- TypeScript (AWS SDK v3) ---
import { ComprehendClient, DetectKeyPhrasesCommand } from "@aws-sdk/client-comprehend";
const comprehend = new ComprehendClient({});
const resp = await comprehend.send(new DetectKeyPhrasesCommand({
Text: "The quarterly earnings report exceeded analyst expectations.",
LanguageCode: "en",
}));
for (const phrase of resp.KeyPhrases ?? []) {
console.log(phrase.Text, phrase.Score);
}BeginOffset/EndOffset, just like entities, so you can highlight it in the source text.Related: Entity & Key Phrase Extraction - combining both signals in one pipeline.
ContainsPiiEntities is a lighter check than DetectPiiEntities - it tells you which PII labels are present and how confidently, without offsets.
# --- Python (boto3) ---
import boto3
comprehend = boto3.client("comprehend")
resp = comprehend.contains_pii_entities(
Text="Contact John at john.doe@example.com or 555-0100.",
LanguageCode="en",
)
for label in resp["Labels"]:
print(label["Name"], label["Score"])// --- TypeScript (AWS SDK v3) ---
import { ComprehendClient, ContainsPiiEntitiesCommand } from "@aws-sdk/client-comprehend";
const comprehend = new ComprehendClient({});
const resp = await comprehend.send(new ContainsPiiEntitiesCommand({
Text: "Contact John at john.doe@example.com or 555-0100.",
LanguageCode: "en",
}));
for (const label of resp.Labels ?? []) {
console.log(label.Name, label.Score);
}DetectPiiEntities call on documents this flags as containing PII.Labels gives entity type names (EMAIL, PHONE, NAME, and others) and scores, but no character offsets.DetectPiiEntities when you need the exact spans to mask.Related: PII Detection & Redaction - the full detect-and-mask workflow.
For a whole S3 prefix of documents instead of one string, start a job and poll it instead of calling Detect in a loop.
# --- Python (boto3) ---
import boto3
comprehend = boto3.client("comprehend")
resp = comprehend.start_sentiment_detection_job(
InputDataConfig={"S3Uri": "s3://my-bucket/reviews/", "InputFormat": "ONE_DOC_PER_LINE"},
OutputDataConfig={"S3Uri": "s3://my-bucket/reviews-out/"},
DataAccessRoleArn="arn:aws:iam::123456789012:role/ComprehendJobRole",
LanguageCode="en",
)
print(resp["JobId"])// --- TypeScript (AWS SDK v3) ---
import { ComprehendClient, StartSentimentDetectionJobCommand } from "@aws-sdk/client-comprehend";
const comprehend = new ComprehendClient({});
const resp = await comprehend.send(new StartSentimentDetectionJobCommand({
InputDataConfig: { S3Uri: "s3://my-bucket/reviews/", InputFormat: "ONE_DOC_PER_LINE" },
OutputDataConfig: { S3Uri: "s3://my-bucket/reviews-out/" },
DataAccessRoleArn: "arn:aws:iam::123456789012:role/ComprehendJobRole",
LanguageCode: "en",
}));
console.log(resp.JobId);DataAccessRoleArn must be an IAM role Comprehend can assume to read the input prefix and write the output prefix.JobId; results land in S3 minutes later.DescribeSentimentDetectionJob with the JobId to watch JobStatus move to COMPLETED or FAILED.Start*Job - entities, key phrases, PII, and dominant language included.Related: Batch vs Real-Time Comprehend Jobs - when to reach for this over a synchronous call.
Stack versions: This page was written for boto3 1.43.x (Python 3.10+) and the AWS SDK for JavaScript v3 (Node.js 18+).
Revisado por Chris St. John·Última actualización: 24 jul 2026