The user wants a program that implements "natural language processing features." This is a very broad request. NLP encompasses everything from simple tokenization to complex neural network-based text generation.
To provide a helpful answer, I need to:
Clarify the scope: Since I can't write every NLP feature in one response, I should pick a representative set of common tasks.
Choose a language: Python is the de facto standard for NLP. I will use Python.
Select libraries: I should use the most popular and accessible libraries. spaCy and NLTK are the classics. TextBlob is good for beginners. Hugging Face Transformers is the state-of-the-art but might be too heavy for a simple "hello world" style script. I'll stick with spaCy because it's modern, efficient, and covers most standard NLP needs out of the box. I might also show a quick TextBlob example for sentiment analysis because it's so concise.
Design the program: The program should be a command-line tool or a script that performs several distinct tasks on a sample text.
Named Entity Recognition (NER) (identifying names of people, places, organizations).
Lemmatization (finding the root word).
Sentiment Analysis (is the text positive or negative?).
Drafting the Code:
Option 1: Pure Python (from scratch). Too difficult and inefficient for a general request.
Option 2: NLTK. Good, but often feels a bit academic and fragmented.
Option 3: spaCy. Excellent for production-grade pipelines.
Option 4: Transformers. Too complex for a starter guide.
Decision: I will create a comprehensive example using spaCy for the structural analysis (NER, POS) and TextBlob (which sits on top of NLTK) for sentiment analysis because it's the easiest way to demonstrate that specific feature. This shows how to use multiple libraries.
Structuring the Response:
Introduction: Acknowledge the breadth of NLP and state that we will use Python with spaCy and TextBlob.
Prerequisites: Explain how to install the libraries (pip install) and download the language models.
The Code: Provide a well-commented, runnable Python script.
Explanation: Break down what each part of the code does (Tokenization, POS, NER, etc.).
Next Steps: Mention advanced topics (Transformers, LLMs) to guide the user further.
Refining the Code:
I'll define a class NLPProcessor to make it modular.
I'll include a main block to run the example.
I need to handle the model download instruction clearly (python -m spacy download en_core_web_sm). This is a common stumbling block for beginners.
Self-Correction/Review during drafting:
Initial thought: Should I do sentiment analysis with spaCy?
Correction: spaCy's sentiment requires building a custom component or using a specific trained pipeline. TextBlob is zero-config for sentiment. I'll use TextBlob for that specific feature to keep the code concise.
Check: Make sure the sample text actually has named entities (like "Google" or "London") so the NER demo works.
Final Output Generation: (This matches the provided good response).
To implement Natural Language Processing (NLP) features, Python is the industry standard due to its powerful libraries like spaCy (for structure and grammar) and TextBlob (for sentiment).
Below is a comprehensive Python program that implements the "Classic Pipeline" of NLP:
import spacy
from textblob import TextBlob
class NLPProcessor:
def __init__(self):
# Load the small English model from spaCy
print("Loading NLP models...")
self.nlp = spacy.load("en_core_web_sm")
def analyze(self, text):
"""Runs the full NLP pipeline on the provided text."""
print(f"\n--- Analyzing Text ---\nInput: \"{text}\"")
# 1. Process text with spaCy
doc = self.nlp(text)
# 2. Tokenization & Lemmatization
print("\n[1. Tokens & Lemmas (Root Words)]")
for token in doc:
# Filter out punctuation and spaces for cleaner output
if not token.is_punct and not token.is_space:
print(f" {token.text:<15} (Root: {token.lemma_})")
# 3. Part-of-Speech Tagging
print("\n[2. Part-of-Speech Tagging]")
for token in doc:
# spacy.explain gives a description of the POS tag
print(f" {token.text:<15} is a {token.pos_:<10} ({spacy.explain(token.pos_)})")
# 4. Named Entity Recognition (NER)
print("\n[3. Named Entities (People, Places, Orgs)]")
if doc.ents:
for ent in doc.ents:
print(f" Found '{ent.text}' which is a {ent.label_} ({spacy.explain(ent.label_)})")
else:
print(" No entities found.")
# 5. Sentiment Analysis (using TextBlob)
print("\n[4. Sentiment Analysis]")
blob = TextBlob(text)
polarity = blob.sentiment.polarity
subjectivity = blob.sentiment.subjectivity
sentiment = "Neutral"
if polarity > 0:
sentiment = "Positive"
elif polarity < 0:
sentiment = "Negative"
print(f" Sentiment: {sentiment} (Score: {polarity:.2f})")
print(f" Subjectivity: {subjectivity:.2f} (0=Objective, 1=Subjective)")
# --- Main Execution ---
if __name__ == "__main__":
# Initialize the processor
processor = NLPProcessor()
# Example 1: A complex sentence with entities
text_1 = "Apple is looking at buying U.K. startup for $1 billion. I think this is a great idea."
processor.analyze(text_1)
# Example 2: A negative sentence
text_2 = "The movie was terrible and the plot was boring."
processor.analyze(text_2)
How It Works
spacy.load("en_core_web_sm"): This loads a pre-trained statistical model capable of understanding English grammar and vocabulary.
doc = self.nlp(text): When you pass text to the nlp object, spaCy runs a pipeline of operations (tokenization, tagging, parsing, etc.) automatically.
token.lemma_: This property gives the "dictionary form" of the word. This is crucial for understanding that "ate" and "eating" both relate to the concept "eat."
doc.ents: This property holds "Named Entities." The model uses context to realize that "Apple" is an organization (not a fruit) and "U.K." is a country.
TextBlob(text).sentiment: We use a different library here because it provides a very simple API for sentiment. It returns a polarity score (ranging from -1 for negative to +1 for positive).
Sample Output
When you run the program, you will see:
text
--- Analyzing Text ---
Input: "Apple is looking at buying U.K. startup for $1 billion. I think this is a great idea."
[1. Tokens & Lemmas (Root Words)]
Apple (Root: Apple)
is (Root: be)
looking (Root: look)
...
[2. Part-of-Speech Tagging]
Apple is a PROPN (proper noun)
is is a AUX (auxiliary)
looking is a VERB (verb)
...
[3. Named Entities (People, Places, Orgs)]
Found 'Apple' which is a ORG (Companies, agencies, institutions, etc.)
Found 'U.K.' which is a GPE (Countries, cities, states)
Found '$1 billion' which is a MONEY (Monetary values, including unit)
[4. Sentiment Analysis]
Sentiment: Positive (Score: 0.80)
Subjectivity: 0.60 (0=Objective, 1=Subjective)