



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




import nltk import spacy from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer, PorterStemmer from nltk import pos_tag
nltk.download('punkt') nltk.download('stopwords') nltk.download('wordnet') nltk.download('averaged_perceptron_tagger')
nlp = spacy.load("en_core_web_sm")
text = """ The quick brown fox jumps over the lazy dog. I saw a man with a telescope. The bank can guarantee deposits will eventually cover future tuition costs. """ print("="60) print("ORIGINAL TEXT") print("="60) print(text)
print("\n" + "="60) print("1. TOKENIZATION") print("="60) nltk_tokens = word_tokenize(text) print("NLTK Tokens:") print(nltk_tokens) spacy_doc = nlp(text) spacy_tokens = [token.text for token in spacy_doc] print("\nspaCy Tokens:") print(spacy_tokens)
print("\n" + "="60) print("2. STOP-WORD REMOVAL") print("="60) stop_words = set(stopwords.words('english'))
nltk_filtered = [word for word in nltk_tokens if word.lower() not in stop_words and word.isalpha()] print("NLTK Stop-word Removed:") print(nltk_filtered) spacy_filtered = [token.text for token in spacy_doc if not token.is_stop and token.is_alpha] print("\nspaCy Stop-word Removed:") print(spacy_filtered)
print("\n" + "="60) print("3. LEMMATIZATION / STEMMING") print("="60) lemmatizer = WordNetLemmatizer() stemmer = PorterStemmer() print("Word\tLemma\tStem") for word in nltk_filtered: lemma = lemmatizer.lemmatize(word) stem = stemmer.stem(word) print(f"{word}\t{lemma}\t{stem}") print("\nspaCy Lemmatization:") for token in spacy_doc: if token.is_alpha: print(f"{token.text} - > {token.lemma_}")
print("\n" + "="60) print("4. POS TAGGING") print("="60) nltk_pos = pos_tag(nltk_tokens) print("NLTK POS Tags:") for word, tag in nltk_pos: print(f"{word}: {tag}") print("\nspaCy POS Tags:") for token in spacy_doc: print(f"{token.text}: {token.pos_}")
print("\n" + "="60) print("5. MORPHOLOGICAL ANALYSIS") print("="60) common_suffixes = ['ing', 'ed', 's', 'es', 'ly', 'ment', 'tion'] def morphological_analysis(word): for suffix in common_suffixes: if word.lower().endswith(suffix) and len(word) > len(suffix):
print("- NLTK is more educational and flexible for learning individual NLP components.")