AI Lab Manual Aktu
AI Lab Manual Aktu
Object:- Write a python program to remove stop words for a given passage from a text file
using NLTK?
Source Code:-
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
def remove_stopwords(file_path):
# Read the passage from the text file
try:
with open(file_path, 'r') as file:
text = file.read()
except FileNotFoundError:
print("The specified file does not exist.")
return
14
# Join the filtered words into a cleaned passage
cleaned_text = ' '.join(filtered_words)
print("Original Passage:")
print(text)
print("\nCleaned Passage:")
print(cleaned_text)
Output:-
15
Program 8
Object:- Write a python program to implement stemming for a given sentence using NLTK?
Source Code:-
import nltk
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
def perform_stemming(sentence):
# Initialize the PorterStemmer
stemmer = PorterStemmer()
print("Original Sentence:")
print(sentence)
print("\nStemmed Sentence:")
print(stemmed_sentence)
# Input sentence
sentence = "The cats are running faster than the dogs, and they will be jumping again soon."
perform_stemming(sentence)
16
Output:-
17
Program 9
Object:- Write a python program to POS (Parts of Speech) tagging for the give sentence
using NLTK?
Source Code:-
import nltk
def pos_tagging(sentence):
# Tokenize the sentence into words
words = nltk.word_tokenize(sentence)
# Input sentence
sentence = "The quick brown fox jumps over the lazy dog."
pos_tagging(sentence)
18
Output:-
19
Program 10
Object:- Write a python program to implement Lemmatization using NLTK?
Source Code:-
import nltk
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
def perform_lemmatization(sentence):
# Initialize the WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
print("Original Sentence:")
print(sentence)
print("\nLemmatized Sentence:")
print(lemmatized_sentence)
20
# Input sentence
sentence = "The leaves are falling from the trees and children are playing in the park."
perform_lemmatization(sentence)
Output:-
21
Program 11
Object:- Write a python program to for Text Classification for the give sentence using NLTK
Source Code:-
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import movie_reviews
from nltk.classify import NaiveBayesClassifier
from nltk.classify.util import accuracy
from nltk.corpus import stopwords
22
train_data = positive_features[:800] + negative_features[:800]
test_data = positive_features[800:] + negative_features[800:]
classifier = NaiveBayesClassifier.train(train_data)
return classifier, test_data
# Main function
def main():
classifier, test_data = train_classifier()
if __name__ == "__main__":
main()
23
Output:-
24