Capítulo 1: Introducción a la PNL
Ejercicios Prácticos
Ejercicio 1: Tokenización con NLTK
Tarea: Utiliza la biblioteca nltk
para tokenizar el siguiente texto: "Natural Language Processing enables computers to understand human language."
Solución:
import nltk
nltk.download('punkt')
from nltk.tokenize import word_tokenize
text = "Natural Language Processing enables computers to understand human language."
tokens = word_tokenize(text)
print(tokens)
Salida:
['Natural', 'Language', 'Processing', 'enables', 'computers', 'to', 'understand', 'human', 'language', '.']
Ejercicio 2: Reconocimiento de Entidades Nombradas con SpaCy
Tarea: Utiliza la biblioteca spaCy
para extraer entidades nombradas del texto: "Google fue fundada por Larry Page y Sergey Brin mientras eran estudiantes de doctorado en la Universidad de Stanford."
Solución:
import spacy
# Load SpaCy model
nlp = spacy.load("en_core_web_sm")
text = "Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University."
doc = nlp(text)
# Extract named entities
for ent in doc.ents:
print(ent.text, ent.label_)
Salida:
Google ORG
Larry Page PERSON
Sergey Brin PERSON
Stanford University ORG
Ejercicio 3: Análisis de Sentimientos con TextBlob
Tarea: Utiliza la biblioteca TextBlob
para analizar el sentimiento del siguiente texto: "Estoy extremadamente feliz con el servicio proporcionado."
Solución:
from textblob import TextBlob
text = "I am extremely happy with the service provided."
blob = TextBlob(text)
sentiment = blob.sentiment
print(sentiment)
Salida:
Sentiment(polarity=0.8, subjectivity=0.75)
Ejercicio 4: Resumen de Texto con sumy
Tarea: Utiliza la biblioteca sumy
para resumir el siguiente texto en dos oraciones:
"Natural Language Processing (NLP) es un campo fascinante en la intersección de la informática, la inteligencia artificial y la lingüística. Permite a las máquinas comprender, interpretar y generar lenguaje humano, abriendo un mundo de posibilidades para aplicaciones que van desde chatbots y servicios de traducción hasta análisis de sentimientos y más allá. La evolución de NLP ha sido impulsada por avances significativos en el aprendizaje automático y el aprendizaje profundo, que han permitido modelos más sofisticados y precisos para la comprensión del lenguaje. Este libro tiene como objetivo llevarte estas técnicas de vanguardia de una manera accesible y práctica, independientemente de tu nivel actual de experiencia."
Solución:
from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.lsa import LsaSummarizer
text = """
Natural Language Processing (NLP) is a fascinating field at the intersection of computer science, artificial intelligence, and linguistics. It enables machines to understand, interpret, and generate human language, opening up a world of possibilities for applications ranging from chatbots and translation services to sentiment analysis and beyond. The evolution of NLP has been driven by significant advances in machine learning and deep learning, which have enabled more sophisticated and accurate models for language understanding. This book aims to bring these cutting-edge techniques to you in an accessible and practical way, regardless of your current level of expertise.
"""
parser = PlaintextParser.from_string(text, Tokenizer("english"))
summarizer = LsaSummarizer()
summary = summarizer(parser.document, 2)
for sentence in summary:
print(sentence)
Salida:
It enables machines to understand, interpret, and generate human language, opening up a world of possibilities for applications ranging from chatbots and translation services to sentiment analysis and beyond.
The evolution of NLP has been driven by significant advances in machine learning and deep learning, which have enabled more sophisticated and accurate models for language understanding.
Ejercicio 5: Clasificación de Texto con scikit-learn
Tarea: Utiliza scikit-learn
para entrenar un clasificador Naive Bayes con los siguientes datos y predecir el sentimiento de un nuevo texto: "Esta experiencia fue fantástica."
Textos:
- "I love this product" (positivo)
- "This is the worst experience" (negativo)
- "Absolutely fantastic!" (positivo)
- "Not good at all" (negativo)
Solución:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
texts = ["I love this product", "This is the worst experience", "Absolutely fantastic!", "Not good at all"]
labels = [1, 0, 1, 0]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)
classifier = MultinomialNB()
classifier.fit(X, labels)
new_text = ["This experience was fantastic"]
X_new = vectorizer.transform(new_text)
prediction = classifier.predict(X_new)
print(prediction)
Salida:
[1]
Estos ejercicios prácticos brindan experiencia práctica con diferentes aspectos de NLP usando Python. Cada ejercicio está diseñado para reforzar los conceptos discutidos en el capítulo y ayudarte a volverte competente en la implementación de técnicas de NLP.
Ejercicios Prácticos
Ejercicio 1: Tokenización con NLTK
Tarea: Utiliza la biblioteca nltk
para tokenizar el siguiente texto: "Natural Language Processing enables computers to understand human language."
Solución:
import nltk
nltk.download('punkt')
from nltk.tokenize import word_tokenize
text = "Natural Language Processing enables computers to understand human language."
tokens = word_tokenize(text)
print(tokens)
Salida:
['Natural', 'Language', 'Processing', 'enables', 'computers', 'to', 'understand', 'human', 'language', '.']
Ejercicio 2: Reconocimiento de Entidades Nombradas con SpaCy
Tarea: Utiliza la biblioteca spaCy
para extraer entidades nombradas del texto: "Google fue fundada por Larry Page y Sergey Brin mientras eran estudiantes de doctorado en la Universidad de Stanford."
Solución:
import spacy
# Load SpaCy model
nlp = spacy.load("en_core_web_sm")
text = "Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University."
doc = nlp(text)
# Extract named entities
for ent in doc.ents:
print(ent.text, ent.label_)
Salida:
Google ORG
Larry Page PERSON
Sergey Brin PERSON
Stanford University ORG
Ejercicio 3: Análisis de Sentimientos con TextBlob
Tarea: Utiliza la biblioteca TextBlob
para analizar el sentimiento del siguiente texto: "Estoy extremadamente feliz con el servicio proporcionado."
Solución:
from textblob import TextBlob
text = "I am extremely happy with the service provided."
blob = TextBlob(text)
sentiment = blob.sentiment
print(sentiment)
Salida:
Sentiment(polarity=0.8, subjectivity=0.75)
Ejercicio 4: Resumen de Texto con sumy
Tarea: Utiliza la biblioteca sumy
para resumir el siguiente texto en dos oraciones:
"Natural Language Processing (NLP) es un campo fascinante en la intersección de la informática, la inteligencia artificial y la lingüística. Permite a las máquinas comprender, interpretar y generar lenguaje humano, abriendo un mundo de posibilidades para aplicaciones que van desde chatbots y servicios de traducción hasta análisis de sentimientos y más allá. La evolución de NLP ha sido impulsada por avances significativos en el aprendizaje automático y el aprendizaje profundo, que han permitido modelos más sofisticados y precisos para la comprensión del lenguaje. Este libro tiene como objetivo llevarte estas técnicas de vanguardia de una manera accesible y práctica, independientemente de tu nivel actual de experiencia."
Solución:
from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.lsa import LsaSummarizer
text = """
Natural Language Processing (NLP) is a fascinating field at the intersection of computer science, artificial intelligence, and linguistics. It enables machines to understand, interpret, and generate human language, opening up a world of possibilities for applications ranging from chatbots and translation services to sentiment analysis and beyond. The evolution of NLP has been driven by significant advances in machine learning and deep learning, which have enabled more sophisticated and accurate models for language understanding. This book aims to bring these cutting-edge techniques to you in an accessible and practical way, regardless of your current level of expertise.
"""
parser = PlaintextParser.from_string(text, Tokenizer("english"))
summarizer = LsaSummarizer()
summary = summarizer(parser.document, 2)
for sentence in summary:
print(sentence)
Salida:
It enables machines to understand, interpret, and generate human language, opening up a world of possibilities for applications ranging from chatbots and translation services to sentiment analysis and beyond.
The evolution of NLP has been driven by significant advances in machine learning and deep learning, which have enabled more sophisticated and accurate models for language understanding.
Ejercicio 5: Clasificación de Texto con scikit-learn
Tarea: Utiliza scikit-learn
para entrenar un clasificador Naive Bayes con los siguientes datos y predecir el sentimiento de un nuevo texto: "Esta experiencia fue fantástica."
Textos:
- "I love this product" (positivo)
- "This is the worst experience" (negativo)
- "Absolutely fantastic!" (positivo)
- "Not good at all" (negativo)
Solución:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
texts = ["I love this product", "This is the worst experience", "Absolutely fantastic!", "Not good at all"]
labels = [1, 0, 1, 0]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)
classifier = MultinomialNB()
classifier.fit(X, labels)
new_text = ["This experience was fantastic"]
X_new = vectorizer.transform(new_text)
prediction = classifier.predict(X_new)
print(prediction)
Salida:
[1]
Estos ejercicios prácticos brindan experiencia práctica con diferentes aspectos de NLP usando Python. Cada ejercicio está diseñado para reforzar los conceptos discutidos en el capítulo y ayudarte a volverte competente en la implementación de técnicas de NLP.
Ejercicios Prácticos
Ejercicio 1: Tokenización con NLTK
Tarea: Utiliza la biblioteca nltk
para tokenizar el siguiente texto: "Natural Language Processing enables computers to understand human language."
Solución:
import nltk
nltk.download('punkt')
from nltk.tokenize import word_tokenize
text = "Natural Language Processing enables computers to understand human language."
tokens = word_tokenize(text)
print(tokens)
Salida:
['Natural', 'Language', 'Processing', 'enables', 'computers', 'to', 'understand', 'human', 'language', '.']
Ejercicio 2: Reconocimiento de Entidades Nombradas con SpaCy
Tarea: Utiliza la biblioteca spaCy
para extraer entidades nombradas del texto: "Google fue fundada por Larry Page y Sergey Brin mientras eran estudiantes de doctorado en la Universidad de Stanford."
Solución:
import spacy
# Load SpaCy model
nlp = spacy.load("en_core_web_sm")
text = "Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University."
doc = nlp(text)
# Extract named entities
for ent in doc.ents:
print(ent.text, ent.label_)
Salida:
Google ORG
Larry Page PERSON
Sergey Brin PERSON
Stanford University ORG
Ejercicio 3: Análisis de Sentimientos con TextBlob
Tarea: Utiliza la biblioteca TextBlob
para analizar el sentimiento del siguiente texto: "Estoy extremadamente feliz con el servicio proporcionado."
Solución:
from textblob import TextBlob
text = "I am extremely happy with the service provided."
blob = TextBlob(text)
sentiment = blob.sentiment
print(sentiment)
Salida:
Sentiment(polarity=0.8, subjectivity=0.75)
Ejercicio 4: Resumen de Texto con sumy
Tarea: Utiliza la biblioteca sumy
para resumir el siguiente texto en dos oraciones:
"Natural Language Processing (NLP) es un campo fascinante en la intersección de la informática, la inteligencia artificial y la lingüística. Permite a las máquinas comprender, interpretar y generar lenguaje humano, abriendo un mundo de posibilidades para aplicaciones que van desde chatbots y servicios de traducción hasta análisis de sentimientos y más allá. La evolución de NLP ha sido impulsada por avances significativos en el aprendizaje automático y el aprendizaje profundo, que han permitido modelos más sofisticados y precisos para la comprensión del lenguaje. Este libro tiene como objetivo llevarte estas técnicas de vanguardia de una manera accesible y práctica, independientemente de tu nivel actual de experiencia."
Solución:
from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.lsa import LsaSummarizer
text = """
Natural Language Processing (NLP) is a fascinating field at the intersection of computer science, artificial intelligence, and linguistics. It enables machines to understand, interpret, and generate human language, opening up a world of possibilities for applications ranging from chatbots and translation services to sentiment analysis and beyond. The evolution of NLP has been driven by significant advances in machine learning and deep learning, which have enabled more sophisticated and accurate models for language understanding. This book aims to bring these cutting-edge techniques to you in an accessible and practical way, regardless of your current level of expertise.
"""
parser = PlaintextParser.from_string(text, Tokenizer("english"))
summarizer = LsaSummarizer()
summary = summarizer(parser.document, 2)
for sentence in summary:
print(sentence)
Salida:
It enables machines to understand, interpret, and generate human language, opening up a world of possibilities for applications ranging from chatbots and translation services to sentiment analysis and beyond.
The evolution of NLP has been driven by significant advances in machine learning and deep learning, which have enabled more sophisticated and accurate models for language understanding.
Ejercicio 5: Clasificación de Texto con scikit-learn
Tarea: Utiliza scikit-learn
para entrenar un clasificador Naive Bayes con los siguientes datos y predecir el sentimiento de un nuevo texto: "Esta experiencia fue fantástica."
Textos:
- "I love this product" (positivo)
- "This is the worst experience" (negativo)
- "Absolutely fantastic!" (positivo)
- "Not good at all" (negativo)
Solución:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
texts = ["I love this product", "This is the worst experience", "Absolutely fantastic!", "Not good at all"]
labels = [1, 0, 1, 0]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)
classifier = MultinomialNB()
classifier.fit(X, labels)
new_text = ["This experience was fantastic"]
X_new = vectorizer.transform(new_text)
prediction = classifier.predict(X_new)
print(prediction)
Salida:
[1]
Estos ejercicios prácticos brindan experiencia práctica con diferentes aspectos de NLP usando Python. Cada ejercicio está diseñado para reforzar los conceptos discutidos en el capítulo y ayudarte a volverte competente en la implementación de técnicas de NLP.
Ejercicios Prácticos
Ejercicio 1: Tokenización con NLTK
Tarea: Utiliza la biblioteca nltk
para tokenizar el siguiente texto: "Natural Language Processing enables computers to understand human language."
Solución:
import nltk
nltk.download('punkt')
from nltk.tokenize import word_tokenize
text = "Natural Language Processing enables computers to understand human language."
tokens = word_tokenize(text)
print(tokens)
Salida:
['Natural', 'Language', 'Processing', 'enables', 'computers', 'to', 'understand', 'human', 'language', '.']
Ejercicio 2: Reconocimiento de Entidades Nombradas con SpaCy
Tarea: Utiliza la biblioteca spaCy
para extraer entidades nombradas del texto: "Google fue fundada por Larry Page y Sergey Brin mientras eran estudiantes de doctorado en la Universidad de Stanford."
Solución:
import spacy
# Load SpaCy model
nlp = spacy.load("en_core_web_sm")
text = "Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University."
doc = nlp(text)
# Extract named entities
for ent in doc.ents:
print(ent.text, ent.label_)
Salida:
Google ORG
Larry Page PERSON
Sergey Brin PERSON
Stanford University ORG
Ejercicio 3: Análisis de Sentimientos con TextBlob
Tarea: Utiliza la biblioteca TextBlob
para analizar el sentimiento del siguiente texto: "Estoy extremadamente feliz con el servicio proporcionado."
Solución:
from textblob import TextBlob
text = "I am extremely happy with the service provided."
blob = TextBlob(text)
sentiment = blob.sentiment
print(sentiment)
Salida:
Sentiment(polarity=0.8, subjectivity=0.75)
Ejercicio 4: Resumen de Texto con sumy
Tarea: Utiliza la biblioteca sumy
para resumir el siguiente texto en dos oraciones:
"Natural Language Processing (NLP) es un campo fascinante en la intersección de la informática, la inteligencia artificial y la lingüística. Permite a las máquinas comprender, interpretar y generar lenguaje humano, abriendo un mundo de posibilidades para aplicaciones que van desde chatbots y servicios de traducción hasta análisis de sentimientos y más allá. La evolución de NLP ha sido impulsada por avances significativos en el aprendizaje automático y el aprendizaje profundo, que han permitido modelos más sofisticados y precisos para la comprensión del lenguaje. Este libro tiene como objetivo llevarte estas técnicas de vanguardia de una manera accesible y práctica, independientemente de tu nivel actual de experiencia."
Solución:
from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.lsa import LsaSummarizer
text = """
Natural Language Processing (NLP) is a fascinating field at the intersection of computer science, artificial intelligence, and linguistics. It enables machines to understand, interpret, and generate human language, opening up a world of possibilities for applications ranging from chatbots and translation services to sentiment analysis and beyond. The evolution of NLP has been driven by significant advances in machine learning and deep learning, which have enabled more sophisticated and accurate models for language understanding. This book aims to bring these cutting-edge techniques to you in an accessible and practical way, regardless of your current level of expertise.
"""
parser = PlaintextParser.from_string(text, Tokenizer("english"))
summarizer = LsaSummarizer()
summary = summarizer(parser.document, 2)
for sentence in summary:
print(sentence)
Salida:
It enables machines to understand, interpret, and generate human language, opening up a world of possibilities for applications ranging from chatbots and translation services to sentiment analysis and beyond.
The evolution of NLP has been driven by significant advances in machine learning and deep learning, which have enabled more sophisticated and accurate models for language understanding.
Ejercicio 5: Clasificación de Texto con scikit-learn
Tarea: Utiliza scikit-learn
para entrenar un clasificador Naive Bayes con los siguientes datos y predecir el sentimiento de un nuevo texto: "Esta experiencia fue fantástica."
Textos:
- "I love this product" (positivo)
- "This is the worst experience" (negativo)
- "Absolutely fantastic!" (positivo)
- "Not good at all" (negativo)
Solución:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
texts = ["I love this product", "This is the worst experience", "Absolutely fantastic!", "Not good at all"]
labels = [1, 0, 1, 0]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)
classifier = MultinomialNB()
classifier.fit(X, labels)
new_text = ["This experience was fantastic"]
X_new = vectorizer.transform(new_text)
prediction = classifier.predict(X_new)
print(prediction)
Salida:
[1]
Estos ejercicios prácticos brindan experiencia práctica con diferentes aspectos de NLP usando Python. Cada ejercicio está diseñado para reforzar los conceptos discutidos en el capítulo y ayudarte a volverte competente en la implementación de técnicas de NLP.