Analyze a given text to extract the entities(with their type) in the text using a Python…
- User
Analyze a given text to extract the entities(with their type) in the text using a Python script. The President Barack Obama was born in Hawaii.
Assistant
Analyze a given text to extract the entities(with their type) in the text using a Python script. The President Barack Obama was born in Hawaii.
Problem: Analyze a given text to extract the entities(with their type) in the text using a Python script. The President Barack Obama was born in Hawaii.
Approach: for production NER tasks
Key considerations:
============================================================
Key Fea
Let me implement this solution.
</think>
## Named Entity Recognition (NER) Feature
### Architectural Decisions
**1. Library Choice: spaCy**
- **Reasoning**: spaCy provides the best balance of accuracy, speed, and ease of use for production NER tasks. Unlike NLTK (more academic), Stanford NER (requires Java), or Transformers (heavyweight), spaCy offers pre-trained models that work out-of-the-box with minimal setup.
**2. Model Selection: `en_core_web_sm`**
- **Reasoning**: The small English model is sufficient for demonstration and quick processing. For production with higher accuracy requirements, `en_core_web_lg` can be substituted.
**3. Output Structure**
- Returns a list of dictionaries with entity text, label, and character positions
- **Reasoning**: This structured format is easily consumable by downstream systems and supports text highlighting use cases.
**4. Modular Design**
- Single-responsibility function that can be imported, tested, and extended independently
---
### Implementation
```python
"""
Named Entity Recognition (NER) Module
Extracts entities and their types from text using spaCy.
"""
import subprocess
import sys
def ensure_spacy_model():
"""
Ensures the spaCy English model is installed.
Downloads it automatically if not present.
"""
try:
import spacy
spacy.load("en_core_web_sm")
except OSError:
print("Downloading spaCy model 'en_core_web_sm'...")
subprocess.check_call([
sys.executable, "-m", "spacy", "download", "en_core_web_sm"
])
def extract_entities(text: str) -> list[dict]:
"""
Extract named entities from the given text.
Args:
text: The input text to analyze.
Returns:
A list of dictionaries, each containing:
- 'text': The entity text
- 'type': The entity type/label
- 'start': Start character position
- 'end': End character position
Example:
>>> extract_entities("Barack Obama was born in Hawaii.")
[
{'text': 'Barack Obama', 'type': 'PERSON', 'start': 0, 'end': 12},
{'text': 'Hawaii', 'type': 'GPE', 'start': 25, 'end': 31}
]
"""
if not text or not text.strip():
return []
# Ensure model is available
ensure_spacy_model()
import spacy
# Load the model
nlp = spacy.load("en_core_web_sm")
# Process the text
doc = nlp(text)
# Extract entities
entities = []
for ent in doc.ents:
entities.append({
"text": ent.text,
"type": ent.label_,
"start": ent.start_char,
"end": ent.end_char
})
return entities
def format_entity_type(label: str) -> str:
"""
Convert spaCy entity labels to human-readable types.
Args:
label: spaCy entity label (e.g., 'GPE', 'PERSON')
Returns:
Human-readable entity type description.
"""
entity_descriptions = {
"PERSON": "Person",
"ORG": "Organization",
"GPE": "Location (Country/City/State)",
"LOC": "Location",
"DATE": "Date",
"TIME": "Time",
"MONEY": "Monetary Value",
"PERCENT": "Percentage",
"QUANTITY": "Quantity",
"CARDINAL": "Cardinal Number",
"ORDINAL": "Ordinal Number",
"NORP": "Nationality/Religious/Political Group",
"FAC": "Facility",
"EVENT": "Event",
"WORK_OF_ART": "Work of Art",
"LAW": "Law",
"LANGUAGE": "Language",
"PRODUCT": "Product",
}
return entity_descriptions.get(label, label)
def main():
"""
Main function to demonstrate entity extraction.
"""
# Input text
text = "The President Barack Obama was born in Hawaii."
print("=" * 60)
print("NAMED ENTITY RECOGNITION")
print("=" * 60)
print(f"\nInput Text:\n \"{text}\"\n")
print("-" * 60)
print("Extracted Entities:\n")
# Extract entities
entities = extract_entities(text)
if not entities:
print(" No entities found.")
else:
for i, entity in enumerate(entities, 1):
readable_type = format_entity_type(entity["type"])
print(f" {i}. {entity['text']}")
print(f" Type: {entity['type']} ({readable_type})")
print(f" Position: {entity['start']}-{entity['end']}")
print()
print("=" * 60)
if __name__ == "__main__":
main()
1. Install dependencies:
pip install spacy
2. Run the script:
python ner_extractor.py
============================================================
NAMED ENTITY RECOGNITION
============================================================
Input Text:
"The President Barack Obama was born in Hawaii."
------------------------------------------------------------
Extracted Entities:
1. Barack Obama
Type: PERSON (Person)
Position: 14-26
2. Hawaii
Type: GPE (Location (Country/City/State))
Position: 39-45
============================================================
| Feature | Description |
|---|---|
| Auto-installation | Automatically downloads the spaCy model if missing |
| Position tracking | Returns character offsets for text highlighting |
| Human-readable types | Converts technical labels to descriptions |
| Empty input handling | Gracefully handles edge cases |
| Modular design | extract_entities() can be imported into other modules |