0% found this document useful (0 votes)
8 views

Programs

Includes some basic program

Uploaded by

kakingareak
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Programs

Includes some basic program

Uploaded by

kakingareak
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

CLASS : II B.

Sc AI
SUBJECT : ARTIFICIAL INTELLIGENCE LAB
SUBJECT CODE : 23UPAI35

LAB EXERCISES

1. Write a python program to implement Breadth First Search Traversal?

2. Write a python program to implement Water Jug Problem?

3. Write a python program to remove punctuations from the given string?

4. Write a python program to sort the sentence in alphabetical order?

5. Write a program to implement Hangman game using python.

6. Write a program to implement Tic-Tac-Toe game using python.

7. Write a python program to remove stop words for a given passage from a text file using NLTK?

8. Write a python program to implement stemming for a given sentence using NLTK?

9. Write a python program to POS (Parts of Speech) tagging for the give sentence using NLTK?

10. Write a python program to implement Lemmatization using NLTK?

11.Write a python program to for Text Classification for the give sentence using NLTK
1. Write a python program to implement Breadth First Search Traversal?

Aim:
To Write a python program to implement Breadth First Search Traversal
Algorithm:

Step 1: Start by putting any one of the graph’s vertices at the back of the queue.

Step 2: Now take the front item of the queue and add it to the visited list.

Step 3: Create a list of that vertex's adjacent nodes. Add those which are not within the visited list to the rear
of the queue.

Step 4: Keep continuing steps two and three till the queue is empty.

Coding:

graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = []
queue = []
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
print("Following is the Breadth-First Search")
bfs(visited, graph, '5')

Output:

Following is the Breadth-First Search


5 37248

Result :
Hence the program is executed and the output is verified.
2.Write a python program to implement Water Jug Problem?

Aim:

To Write a python program to implement Water Jug Problem

Algorithm:

Step 1: Initialization:
BFS Setup:
 Use a queue (deque from collections) to explore each state of the jugs.
 Maintain a visited set to avoid processing the same state multiple times.
 path dictionary is used to track the previous state for each state, helping in reconstructing
the solution once the target is reached.
Step 2:BFS Exploration:
Queue Initialization:
 Start with the initial state (0, 0) where both jugs are empty.
 Mark (0, 0) as visited.
Processing States:
 Dequeue the current state (jug1, jug2).
 Check if either jug1 or jug2 is equal to target. If yes, construct the solution path back to
(0, 0) and return it.
Generating Next States:
 Calculate all possible states that can be reached from the current state by:
 Filling either jug to its capacity.
 Emptying either jug.
 Pouring water from one jug to another until one of them is either empty or full.
Checking Validity:
 For each generated state, check if it has been visited. If not, add it to visited, record its
parent state in path, and enqueue it for further exploration.
Step 3: Completion:
 If the BFS completes without finding a solution (queue becomes empty), return None.

Coding:

from collections import deque


def water_jug_problem(capacity_jug1, capacity_jug2, target):
# BFS initialization
queue = deque([(0, 0)])
visited = set((0, 0))
path = {}
while queue:
current_state = queue.popleft()
jug1, jug2 = current_state
# Check if target is achieved
if jug1 == target or jug2 == target:
# Reconstruct the path
solution_path = []
state = current_state
while state != (0, 0):
solution_path.append(state)
state = path[state]
solution_path.append((0, 0))
solution_path.reverse()
return solution_path
next_states = []
next_states.append((capacity_jug1, jug2))
next_states.append((jug1, capacity_jug2))
next_states.append((0, jug2))
next_states.append((jug1, 0))
pour_amount = min(jug1, capacity_jug2 - jug2)
next_states.append((jug1 - pour_amount, jug2 + pour_amount))
pour_amount = min(jug2, capacity_jug1 - jug1)
next_states.append((jug1 + pour_amount, jug2 - pour_amount))
for state in next_states:
if state not in visited:
visited.add(state)
path[state] = current_state
queue.append(state)
return None
capacity_jug1 = 4
capacity_jug2 = 3
target = 2
solution = water_jug_problem(capacity_jug1, capacity_jug2, target)
if solution:
print(f"Solution found: {solution}")
else:
print("No solution found.")

Output:

Solution found: [(0, 0), (0, 3), (3, 0), (3, 3), (4, 2)]

Result :

Hence the program is executed and the output is verified.


3.Write a python program to remove punctuations from the given string?

Aim:

To Write a python program to remove punctuations from the given string

Algorithm:

Step 1:Define Punctuation Set:


 Create a string punctuations that contains all the punctuation characters you want to remove from the input
string. For example:
Step 2:
Input String:
 Initialize a string variable my_str with the input string you want to process
Step 3:
Remove Punctuation:
 Initialize an empty string no_punctuations to store the result string without punctuation.
 Iterate through each character char in my_str.
 Check if the character char is not in the punctuations set
 If char is not in punctuations, append char to no_punctuations.
Step 4:
Output the Result:
 Print the original string my_str to show what the input was.
 Print no_punctuations to display the string with punctuation removed.

Coding:

punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
my_str = "Hi!!!, Welcome to ---Islamiah @#) College."
# To take input from the user
# my_str = input("Enter a string: ")
# remove punctuation from the string
no_punctuations = ""
for char in my_str:
if char not in punctuations:
no_punctuations = no_punctuations + char
print(“original string: “,my_str)
print(“without punctuations: “,no_puntuations)

Output:

original string: Hi!!!, Welcome to ---Islamiah @#) College.


without punctuations: Hi Welcome to Islamiah College

Result :
Hence the program is executed and the output is verified.
4.Write a python program to sort the sentence in alphabetical order?

Aim:
To Write a python program to sort the sentence in alphabetical order

Algorithm :

Step 1:Import Necessary Libraries:


Import the string module to handle punctuation.
Step 2:Preprocess Sentence:
Define a function preprocess_sentence(sentence) to preprocess the input sentence.
o Convert the sentence to lowercase.
o Remove punctuation from the sentence.
o Return the preprocessed sentence.
Step 3: Sort Sentence:
Define a function sort_sentence(sentence) to sort the words in the sentence.
o Call preprocess_sentence(sentence) to preprocess the sentence.
o Split the sentence into a list of words using split().
o Sort the list of words alphabetically using sort().
o Join the sorted list of words back into a single string using join().
o Return the sorted sentence.
Step 4: Main Function:
Define a main() function to handle user input and output.
o Prompt the user to enter a sentence using input().
o Call sort_sentence(sentence) to get the sorted sentence.
o Print the original sentence.
o Print the sorted sentence.
Step 5: Execute Main Function:
o Use the if __name__ == "__main__": construct to ensure that the main() function is
called when the script is executed.

Coding:

import string
def preprocess_sentence(sentence):
sentence = sentence.lower()
sentence = sentence.translate(str.maketrans('', '', string.punctuation))
return sentence
def sort_sentence(sentence):
sentence = preprocess_sentence(sentence)
words = sentence.split()
words.sort()
sorted_sentence = ' '.join(words)
return sorted_sentence
def main():
sentence = input("Enter a sentence: ")
sorted_sentence = sort_sentence(sentence)
print("\nOriginal sentence: ", sentence)
print("Sorted sentence: ", sorted_sentence)
if __name__ == "__main__":
main()
Output:

Enter a sentence: Artificial Intelligence is a Branch of Computer Science

Original sentence: Artificial Intelligence is a Branch of Computer Science


Sorted sentence: a artificial branch computer intelligence is of science

Result :
Hence the program is executed and the output is verified.
5.Write a program to implement Hangman game using python

Aim:
To Write a program to implement Hangman game using python

Algorithm:

Step 1: Input Player's Name


Prompt the user to enter their name.
Display a welcome message with their name.
Step 2: Display Game Instructions
Inform the player that they will be guessing computer parts.
Step 3: Choose a Random Word
Select a random word from a list of computer-related parts (keyboard, mouse, monitor, etc.).
Step 4: Initialize Game Variables
guesses is an empty string to store the characters guessed by the player.
turns is initialized to 7, which is the number of incorrect guesses allowed.
Step 5: Main Game Loop
Repeat until either the player wins (correctly guesses all characters) or loses (runs out of turns).
Step 6: Loop Through Word Characters
For each character in the chosen word, check if it has been guessed:
If guessed, display the character.
If not guessed, display an underscore (_) in its place.
Track the number of unguessed characters.
Step 7: Check for Win Condition
If there are no more unguessed characters, display a winning message and end the game.
Step 8: Prompt for a Character Guess
Ask the player to input a character guess.
Add the guessed character to the list of guesses.
Step 9: Check if Guess is Correct
If the guess is correct, continue the game.
If the guess is incorrect (not in the word):
Decrease the number of remaining turns by 1.
Inform the player they guessed incorrectly and display the remaining number of guesses.
Step 10: Check for Loss Condition
If the player runs out of turns (turns = 0), display a "You Lose" message and reveal the word.
Step 11: End the Game
The game ends either when the player wins or loses.

Coding:

import random
name = input("What is your name? ")
print("Good Luck!", name)
print("Guess the computer parts!!!")
words = ['keyboard', 'mouse', 'monitor', 'printer', 'joystick', 'projector']
word = random.choice(words)
guesses = ''
turns = 7
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print(char, end=" ")
else:
print("_", end=" ")
failed += 1
print()
if failed == 0:
print("You Win!")
print("The word is:", word)
break
guess = input("Guess a character: ")
guesses += guess
if guess not in word:
turns -= 1 # Reduce the number of turns left
print("Wrong guess!")
print("You have", turns, "more guesses")
if turns == 0:
print("You Lose!")
print("The word was:", word)

Output 1:

What is your name? Alice


Good Luck! Alice
Guess the computer parts!!!
_______
Guess a character: m
m______
Guess a character: o
mo___o_
Guess a character: n
mon__o_
Guess a character: z
Wrong guess!
You have 6 more guesses
mon__o_
Guess a character: i
moni_o_
Guess a character: t
monito_
Guess a character: r
monitor
You Win!
The word is: monitor
Output 2:

What is your name? Bob


Good Luck! Bob
Guess the computer parts!!!
_______
Guess a character: x
Wrong guess!
You have 6 more guesses
_______
Guess a character: y
Wrong guess!
You have 5 more guesses
_______
Guess a character: z
Wrong guess!
You have 4 more guesses
_______
Guess a character: q
Wrong guess!
You have 3 more guesses
_______
Guess a character: w
Wrong guess!
You have 2 more guesses
_______
Guess a character: e
Wrong guess!
You have 1 more guesses
_______
Guess a character: p
Wrong guess!
You Lose!
The word was: monitor

Result :
Hence the program is executed and the output is verified.
6.Write a program to implement Tic-Tac-Toe game using python.

Aim:
To Write a program to implement Tic-Tac-Toe game using python.

Algorithm:
Step 1: Initialize the Board:
 Create a 3x3 board filled with spaces to represent empty cells.
Step 2: Print Board:
 Define a function print_board(board) to display the current state of the board.
Step 3: Check Win Condition:
 Define a function check_win(board, player) to check if a player has won by comparing all possible
winning combinations.
Step 5:Check Draw Condition:
 Define a function check_draw(board) to check if the board is full and there are no empty cells left,
resulting in a draw.
Step 6: Minimax Algorithm:
 Define a recursive function minimax(board, depth, is_maximizing) to evaluate the best possible
move for the AI using the Minimax algorithm:
o If the AI wins, return a score of 1.
o If the human wins, return a score of -1.
o If the game is a draw, return a score of 0.
o If it's the AI's turn (maximizing player), loop through all possible moves, place 'O', call
minimax recursively, undo the move, and return the maximum score.
o If it's the human's turn (minimizing player), loop through all possible moves, place 'X', call
minimax recursively, undo the move, and return the minimum score.
Step 7: Best Move for AI:
 Define a function best_move(board) to determine the best possible move for the AI using the
minimax function:
o Loop through all possible moves, place 'O', call minimax to evaluate the move, undo the
move, and keep track of the move with the highest score.
Step 8: Main Game Loop:
 Define a function play_game() to handle the game flow:
o Print the initial empty board.
o While the game is ongoing:
 Human Player's Turn:
 Prompt the human player to enter their move (row and column).
 If the move is valid, place an 'X' on the board and print the updated board.
 Check if the human player has won or if the game is a draw.
 AI's Turn:
 Determine the best move for the AI using best_move(board), place an 'O' on
the board, and print the updated board.
 Check if the AI has won or if the game is a draw.
Step 9: Play the Game:
 Call the play_game() function to start the game.
Coding:

import math

def print_board(board):

for row in board:

print(" | ".join(row))

print("-" * 9)

def check_win(board, player):

win_states = [

[board[0][0], board[0][1], board[0][2]],

[board[1][0], board[1][1], board[1][2]],

[board[2][0], board[2][1], board[2][2]],

[board[0][0], board[1][0], board[2][0]],

[board[0][1], board[1][1], board[2][1]],

[board[0][2], board[1][2], board[2][2]],

[board[0][0], board[1][1], board[2][2]],

[board[2][0], board[1][1], board[0][2]],

if [player, player, player] in win_states:

return True

return False

def check_draw(board):

for row in board:

if " " in row:

return False

return True

def minimax(board, depth, is_maximizing):

if check_win(board, "O"):

return 1

elif check_win(board, "X"):


return -1

elif check_draw(board):

return 0

if is_maximizing:

best_score = -math.inf

for i in range(3):

for j in range(3):

if board[i][j] == " ":

board[i][j] = "O"

score = minimax(board, depth + 1, False)

board[i][j] = " "

best_score = max(score, best_score)

return best_score

else:

best_score = math.inf

for i in range(3):

for j in range(3):

if board[i][j] == " ":

board[i][j] = "X"

score = minimax(board, depth + 1, True)

board[i][j] = " "

best_score = min(score, best_score)

return best_score

def best_move(board):

best_score = -math.inf

move = (0, 0)

for i in range(3):

for j in range(3):

if board[i][j] == " ":

board[i][j] = "O"
score = minimax(board, 0, False)

board[i][j] = " "

if score > best_score:

best_score = score

move = (i, j)

return move

def play_game():

board = [[" " for _ in range(3)] for _ in range(3)]

print_board(board)

while True:

# Human player's turn

row, col = map(int, input("Enter your move (row and column): ").split())

if board[row][col] == " ":

board[row][col] = "X"

else:

print("Invalid move. Try again.")

continue

print_board(board)

if check_win(board, "X"):

print("You win!")

break

elif check_draw(board):

print("It's a draw!")

break

# AI's turn

ai_row, ai_col = best_move(board)

board[ai_row][ai_col] = "O"

print_board(board)

if check_win(board, "O"):

print("AI wins!")
break

elif check_draw(board):

print("It's a draw!")

break

play_game()

Output 1:

| |
---------
| |
---------
| |

Enter your move (row and column): 1 1


| |
---------
|X|
---------
| |
---------
| |
---------
|O|
---------
| |

Enter your move (row and column): 0 0


X| |
---------
|X|
---------
| |
---------
X|O|
---------
|O|
---------
| |

AI wins!

Output 2:
| |
---------
| |
---------
| |
Enter your move (row and column): 0 0
X| |
---------
| |
---------
| |
---------
X|O|
---------
| |
---------
| |

Enter your move (row and column): 0 1


X|X|
---------
|O|
---------
| |
---------
X|O|
---------
| |
---------
|O|

It's a draw!

Result :
Hence the program is executed and the output is verified.
7. Write a python program to remove stop words for a given passage from a text file using NLTK?

Aim:

To Write a python program to remove stop words for a given passage from a text file using NLTK

Algorithm:

Step 1: Import NLTK Libraries:


o Import necessary NLTK modules: nltk, stopwords, and word_tokenize for tokenization.
Step 2: Download NLTK Resources:
o Download NLTK resources (stopwords and punkt) if not already downloaded on the
system.
Step 3: Define remove_stopwords Function:
o Input: text (a string containing the text to be processed).
o Output: filtered_text (a string with stopwords removed).
o Steps:
 Tokenize the input text into individual words using word_tokenize.
 Retrieve a set of English stopwords using stopwords.words('english').
 Filter out words that are not in the stop_words set (case insensitive comparison).
 Join the filtered words back into a single string separated by spaces.
 Return filtered_text.
Step 4: Define main Function:
o Steps:
 Open and read the contents of the file named input.txt.
 Pass the read text to remove_stopwords function to get cleaned_text.
 Print the original text and the cleaned text.
Step 5 :Execution:
o Check if the script is being run directly (if __name__ == "__main__").
o Call the main function to execute the processing.

Coding:

import nltk

from nltk.corpus import stopwords

from nltk.tokenize import word_tokenize

nltk.download('stopwords')

nltk.download('punkt')

def remove_stopwords(text):

words = word_tokenize(text)

stop_words = set(stopwords.words('english'))

filtered_words = [word for word in words if word.lower() not in stop_words]

filtered_text = ' '.join(filtered_words)


return filtered_text

def main():

with open('input.txt', 'r') as file:

text = file.read()

cleaned_text = remove_stopwords(text)

print("Original Text:")

print(text)

print("\nText after removing stopwords:")

print(cleaned_text)

if __name__ == "__main__":

main()

Output:

Original Text:
This is an example sentence demonstrating the removal of stopwords from text.

Text after removing stopwords:


example sentence demonstrating removal stopwords text .

Result :
Hence the program is executed and the output is verified.
8.Write a python program to implement stemming for a given sentence using NLTK?

Aim:

To Write a python program to implement stemming for a given sentence using NLTK

Algorithm:

Step 1: Import NLTK Libraries:


o Import necessary NLTK modules: nltk, word_tokenize, and PorterStemmer for
stemming.
Step 2: Download NLTK Resources:
o Download NLTK's punkt resource if not already downloaded on the system. This is
required for tokenization.
Step 3: Define stem_sentence Function:
o Input: sentence (a string containing the sentence to be stemmed).
o Output: stemmed_sentence (a string with words stemmed to their root form).
o Steps:
 Tokenize the input sentence into individual words using word_tokenize.
 Initialize a PorterStemmer object (porter).
 Apply stemming to each word in the tokenized list using porter.stem(word).
 Join the stemmed words back into a single string separated by spaces.
 Return stemmed_sentence.
Step 4: Example Usage:
o Define a sample sentence.
o Call stem_sentence with the sentence to obtain stemmed_sentence.
o Print both the original and stemmed sentences for demonstration.

Coding:

import nltk

from nltk.tokenize import word_tokenize

from nltk.stem import PorterStemmer

nltk.download('punkt')

def stem_sentence(sentence):

words = word_tokenize(sentence)

porter = PorterStemmer()

stemmed_words = [porter.stem(word) for word in words]

stemmed_sentence = ' '.join(stemmed_words)

return stemmed_sentence

sentence = "Stemming is used to reduce words to their root form."

stemmed_sentence = stem_sentence(sentence)

print("Original Sentence:", sentence)


print("Stemmed Sentence:", stemmed_sentence)

Output:

Original Sentence: Stemming is used to reduce words to their root form.


Stemmed Sentence: stem is use to reduc word to their root form .

Result :
Hence the program is executed and the output is verified.
9.Write a python program to POS (Parts of Speech) tagging for the give sentence using NLTK?

Aim:

To Write a python program to POS (Parts of Speech) tagging for the give sentence using NLTK

Algorithm:

Step 1: Import the NLTK Library:

o Import the Natural Language Toolkit (NLTK) library, which provides tools for natural
language processing.

Step 2: Download Necessary NLTK Data:

o Use nltk.download('punkt') to download the tokenizer models.


o Use nltk.download('averaged_perceptron_tagger') to download the POS tagger.

Step 3: Define the Input Sentence:

o Create a string variable called sentence that contains the text you want to analyze.
o Example: sentence = "NLTK is a leading platform for building Python
programs to work with human language data."

Step 4: Tokenize the Sentence:

o Use nltk.word_tokenize(sentence) to split the sentence into individual words


(tokens).
o Store the tokens in a variable (e.g., tokens).

Step 5: Perform Part-of-Speech Tagging:

o Use nltk.pos_tag(tokens) to assign POS tags to each token. This identifies the
grammatical category of each word (e.g., noun, verb, adjective).
o Store the POS tags in a variable (e.g., pos_tags).

Ste 6: Print the Result:

o Use print(pos_tags) to display the list of tokens along with their corresponding POS
tags.
CODING:

import nltk

nltk.download('punkt')

nltk.download('averaged_perceptron_tagger')

sentence="NLTK is a leading platform form building python program to work with human
language date."

tokens=nltk.word_tokenize(sentence)

pos_tags=nltk.pos_tag(tokens)

print(pos_tags)
OUTPUT:
[('NLTK', 'NNP'), ('is', 'VBZ'), ('a', 'DT'), ('leading', 'VBG'), ('platform', 'NN'), ('form', 'NN'),
('building', 'NN'), ('python', 'NN'), ('program', 'NN'), ('to', 'TO'), ('work', 'VB'), ('with', 'IN'),
('human', 'JJ'), ('language', 'NN'), ('date', 'NN'), ('.', '.')]

RESULT :

Hence the program is executed and the output is verified.


10.Write a python program to implement Lemmatization using NLTK?

Aim:
To write a python program to implement Lemmatization using NLTK

Alogrithm:

Step 1: Import Required Libraries:

o Import necessary components from the NLTK library such as WordNetLemmatizer and
word_tokenize.

Step 2:Download Required Data:

o Download the wordnet and punkt resources, which are essential for lemmatization and
tokenization respectively.

Step 3: Input Text:

o Define the text to be processed. In this case: "The foxes are quick and they're jumping
over the sleeping dogs".

Step 4: Tokenize the Text:

o Split the input text into individual words using the word_tokenize function. This breaks
the text into tokens (words and punctuation marks).

Step 5: Initialize WordNet Lemmatizer:

o Create an instance of WordNetLemmatizer, which is used to convert words into their


base form (lemma).

Step 6: Lemmatize Each Token:

o Apply the lemmatize() method from the WordNetLemmatizer to each token (word) in
the list. This method looks up the base form (lemma) of each word. By default, it treats
every word as a noun unless otherwise specified.

Step 7: Rejoin Lemmatized Words:

o After lemmatizing the tokens, the processed words are joined back into a single string
with spaces between them.

Step 8: Output the Result:

o Print the original and lemmatized versions of the text for comparison.
Coding:

import nltk

from nltk.stem import WordNetLemmatizer

from nltk.tokenize import word_tokenize

nltk.download('wordnet')

nltk.download('punkt')

text = "The children are playing outside .They enjoy their games and laugh together. Each

child has a unique talent "

words = word_tokenize(text)

lemmatizer = WordNetLemmatizer()

lemmatized_words = [lemmatizer.lemmatize(word) for word in words]

lemmatized_text = ' '.join(lemmatized_words)

print("Original text:")

print(text)

print("\nLemmatized text:")

print(lemmatized_text)
Output:

Original Text:
The children are playing outside .They enjoy their games and laugh together. Each child has a
unique talent

Lemmatized Text:
The child are playing outside .They enjoy their game and laugh together. Each child ha a unique
talent

Result :

Hence the program is executed and the output is verified.


11.Write a python program to for Text Classification for the give sentence using NLTK

Aim:

To Write a python program to for Text Classification for the give sentence using NLTK

Algorithm :

Step 1: Import Libraries:

o Import necessary modules from NLTK (Natural Language Toolkit) like tokenize,
NaiveBayesClassifier, and stopwords.

Step 2: Download NLTK Resources:

o Download required datasets from NLTK, such as word tokenizers (punkt) and English
stopwords (stopwords).

Step 3: Preprocessing Function:

o Define a function preprocess that:


 Converts the text to lowercase.
 Tokenizes the text into words.
 Removes stopwords (common words like "the", "is") and punctuation.
 Returns the remaining words as a dictionary for classification.

Step 4:Create Training Data:

o Prepare a small set of labeled sentences (training data) where each sentence is either
"positive" or "negative".

Step 5: Preprocess Training Data:

o Apply the preprocess function to each sentence in the training data, transforming them
into a format suitable for the classifier.

Step 6: Train Classifier:

o Train a Naive Bayes classifier using the preprocessed training data.

Step 7: Classify New Sentence:


o Preprocess the new test sentence in the same way as the training data.
o Use the trained classifier to predict the label (positive or negative) of the test sentence.

Step 8: Print Result:

o Print the classified label (either "positive" or "negative") for the test sentence.

CODING :

import nltk
from nltk.tokenize import word_tokenize
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import stopwords
import string

# Download necessary NLTK data (run once)


nltk.download('punkt')
nltk.download('stopwords')

# Preprocessing function: remove stopwords and punctuation


def preprocess(text):
stop_words = set(stopwords.words('english'))
words = word_tokenize(text.lower())
words = [word for word in words if word.isalpha() and word not in stop_words]
return {word: True for word in words}

# Sample training data: (Text, Label)


train_data = [
("I love sunny days", "positive"),
("This is a horrible movie", "negative"),
("The food was amazing", "positive"),
("I hate getting wet in the rain", "negative"),
]
# Preprocess training data
train_features = [(preprocess(text), label) for text, label in train_data]

# Train Naive Bayes classifier


classifier = NaiveBayesClassifier.train(train_features)

# Test sentence
test_sentence = "I love this amazing weather"

# Preprocess and classify test sentence


test_features = preprocess(test_sentence)
label = classifier.classify(test_features)

print(f"The sentence is classified as: {label}")

OUTPUT:
The sentence is classified as: positive

RESULT :
Hence the program is executed and the output is verified.

You might also like