Artificial Intelligence Lab Manual: ACADEMIC YEAR: 2019-2020 Second Semester

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

ARTIFICIAL INTELLIGENCE

LAB MANUAL

ACADEMIC YEAR: 2019-2020

SECOND SEMESTER

COURSE NAME : ARTIFICIAL INTELLIGENCE


COURSE CODE : 241 COMP-3
LEVEL : VI

DEPARTMENT : COMPUTER SCIENCE

COLLEGE : COLLEGE OF COMPUTER SCIENCE &


INFORMATION TECHNOLOGY

COURSE COORDINATOR: DR. RAJAN JOHN


AI Lab Manual

LIST OF PROGRAMS
PROGRAM TITLE OF THE PROGRAM PAGE
NO NUMBER
1. ( a ) Write a python program to print the multiplication table for the given 4
number.
(b) Write a python program to check whether the given number is prime or 4
not.
(c) Write a python program to find factorial of the given number. 5
2. Write a python program to implement simple Chatbot. 6

3. ( a ) Write a python program to implement List operations (Nested List, 8


Length, Concatenation, Membership, Iteration, Indexing and Slicing).
(b) Write a python program to implement List methods (Add, Append, 10
Extend & Delete).
4. ( a ) Illustrate Different Set Operations with the help of python program. 12
(b) Generate Calendar for the given month and year using a python program. 12
(c) Write a python program to implement Simple Calculator program 13
5. Write a python program to solve N Queen problem using backtracking. 15
6. Write a python program to implement Breadth First Search Traversal. 19
7. Write a python program to implement Depth First Search Traversal. 22
8. Write a python program to implement Water Jug Problem. 23

9. ( a ) Write a python program to remove punctuations from the given string. 25


(b) Write a python program to sort the sentence in alphabetical order. 25
10. Write a program to implement Hangman game using python. 26
11. ( a ) Write a python program to remove stop words for a given passage from a 30
text file using NLTK.
(b) Write a python program to implement stemming for a given sentence 32
using NLTK.
(c) Write a python program to POS (Parts of Speech) tagging for the give 32
sentence using NLTK.
12. ( a ) Write a python program to implement Lemmatization using NLTK. 33
(b) Write a python program to for Text Classification for the give sentence using 33
NLTK.

Course Code: COMP 241 1


AI Lab Manual

AI WITH PYTHON

Since the invention of computers or machines, their capability to perform various tasks has experienced
an exponential growth. Humans have developed the power of computer systems in terms of their diverse
working domains, their increasing speed, and reducing size with respect to time.
A branch of Computer Science named Artificial Intelligence pursues creating the computers or machines
as intelligent as human beings.

BASIC CONCEPT OF ARTIFICIAL INTELLIGENCE (AI)

According to the father of Artificial Intelligence, John McCarthy, it is “The science and engineering of
making intelligent machines, especially intelligent computer programs”.
Artificial Intelligence is a way of making a computer, a computer-controlled robot, or a software think
intelligently, in the similar manner the intelligent humans think. AI is accomplished by studying how
human brain thinks and how humans learn, decide, and work while trying to solve a problem, and then
using the outcomes of this study as a basis of developing intelligent software and systems.
While exploiting the power of the computer systems, the curiosity of human, lead him to wonder, “Can a
machine think and behave like humans do?”
Thus, the development of AI started with the intention of creating similar intelligence in machines that
we find and regard high in humans.

WHY PYTHON FOR AI

Artificial intelligence is considered to be the trending technology of the future. Already there are a number
of applications made on it. Due to this, many companies and researchers are taking interest in it. But the
main question that arises here is that in which programming language can these AI applications be
developed? There are various programming languages like Lisp, Prolog, C++, Java and Python, which
can be used for developing applications of AI. Among them, Python programming language gains a huge
popularity and the reasons are as follows:

Simple syntax & less coding

Python involves very less coding and simple syntax among other programming languages which can be
used for developing AI applications. Due to this feature, the testing can be easier and we can focus more
on programming.

Inbuilt libraries for AI projects

A major advantage for using Python for AI is that it comes with inbuilt libraries. Python has libraries for
almost all kinds of AI projects. For example, NumPy, SciPy, matplotlib, nltk, SimpleAI are some the

Course Code: COMP 241 2


AI Lab Manual

important inbuilt libraries of Python.


 Open source: Python is an open source programming language. This makes it widely popular in
the community.
 Can be used for broad range of programming: Python can be used for a broad range of
programming tasks like small shell script to enterprise web applications. This is another reason
Python is suitable for AI projects.

FEATURES OF PYTHON

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed
to be highly readable. It uses English keywords frequently where as other languages use punctuation, and
it has fewer syntactical constructions than other languages. Python's features include the following −
 Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
 Easy-to-read − Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain − Python's source code is fairly easy-to-maintain.
 A broad standard library − Python's bulk of the library is very portable and crossplatform
compatible on UNIX, Windows, and Macintosh.
 Interactive Mode − Python has support for an interactive mode which allows interactive testing
and debugging of snippets of code.
 Portable − Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.
 Extendable − We can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
 Databases − Python provides interfaces to all major commercial databases.
 GUI Programming − Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.
 Scalable − Python provides a better structure and support for large programs than shell scripting.

IMPORTANT FEATURES OF PYTHON

Let us now consider the following important features of Python:

 It supports functional and structured programming methods as well as OOP.


 It can be used as a scripting language or can be compiled to byte-code for building large
applications.
 It provides very high-level dynamic data types and supports dynamic type checking.
 It supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Course Code: COMP 241 3


AI Lab Manual

1. (a). Write a python program to print the multiplication table for the given
number?
Code:
# Python program to find the multiplication table (from 1 to 10) of a number
input by the user

# take input from the user

num = int(input("Display multiplication table of? "))

# use for loop to iterate 10 times

for i in range(1,11):

print(num,'x',i,'=',num*i)

Output:

Display multiplication table of? 5


5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

(b). Write a python program to check whether the given number is prime or not?

Code:

# Python program to check if the input number is prime or not

#num = 407

# take input from the user


num = int(input("Enter a number: "))

# prime numbers are greater than 1


if num > 1:
rem=1

for i in range(2,num):
rem=num%i
if rem == 0:
break

Course Code: COMP 241 4


AI Lab Manual

if rem == 0:
print(num,"is not a prime number")
else:
print(num,"is a prime number")

# if input number is less than


# or equal to 1, it is not prime
else:
print(num,"is not a prime number")
Output:

Enter a number: 5

5 is a prime number

(c). Write a python program to find factorial of the given number?


Code:

def recur_factorial(n):

"""Function to return the factorial

of a number using recursion"""

if n == 1:

return n

else:

return n*recur_factorial(n-1)

# Change this value for a different result

#num = 5

# uncomment to take input from the user

num = int(input("Enter a number: "))

# check is the number is negative

if num < 0:

print("Sorry, factorial does not exist for negative numbers")

elif num == 0:

print("The factorial of 0 is 1")

else:

Course Code: COMP 241 5


AI Lab Manual

print("The factorial of",num,"is",recur_factorial(num))

Output:

Enter a number: 5

The factorial of 5 is 120

2. Write a python program to implement simple Chatbot?

Code:

print("Simple Question and Answering Program")

print("=====================================")

print(" You may ask any one of these questions")

print("Hi")

print("How are you?")

print("Are you working?")

print("What is your name?")

print("what did you do yesterday?")

print("Quit")

while True:

question = input("Enter one question from above list:")

question = question.lower()

if question in ['hi']:

print("Hello")

elif question in ['how are you?','how do you do?']:

print("I am fine")

elif question in ['are you working?','are you doing any job?']:

print("yes. I'am studying in Jazan University")

elif question in ['what is your name?']:

print("My name is Emil")

name=input("Enter your name?")

Course Code: COMP 241 6


AI Lab Manual

print("Nice name and Nice meeting you",name)

elif question in ['what did you do yesterday?']:

print("I played Football yesterday")

elif question in ['quit']:

break

else:

print("I don't understand what you said")

Output:

Simple Question and Answering Program

==============================

You may ask any one of these questions

Hi

How are you?

Are you working?

What is your name?

what did you do yesterday?

Quit

Enter one question from above list:hi

Hello

Enter one question from above list:how are you?

I am fine

Enter one question from above list:are you working?

yes. I'am studying in Jazan University

Enter one question from above list:what is your name?

My name is Emil

Enter your name? John

Course Code: COMP 241 7


AI Lab Manual

Nice name and Nice meeting you John

Enter one question from above list:quit

3. (a) Write a python program to implement list operations (Nested


List, Length, Concatenation,Membership,Iteration,Indexing and Slicing)?
Code:

my_list = ['p','r','o','b','e']

# Output: p

print(my_list[0])

print("Length",my_list,":",len(my_list))

# Output: o

print(my_list[2])

# Output: e

print(my_list[4])

# Error! Only integer can be used for indexing

#my_list[4.2]

# Nested List

n_list = [[1,3,5,7], [2,4,6,8,10]]

# Nested indexing

# Output: 3

print(n_list[0][1])

# Output: 8

print(n_list[1][3])

# Nested List2

n_list2 = ["Happy", [2,0,1,5]]

Course Code: COMP 241 8


AI Lab Manual

# Nested indexing

# Output: a

print(n_list2[0][1])

# Output: 5

print(n_list2[1][3])

concat1=[1,3,5]

concat2=[7,8,9]

print("Concatenation:",concat1,concat2,":",concat1+concat2)

repetion_string="Hello"

print("Repetition:",repetion_string,repetion_string * 4)

Output:

Length ['p', 'r', 'o', 'b', 'e']: 5

Concatenation: [1, 3, 5] [7, 8, 9] : [1, 3, 5, 7, 8, 9]

Repetition: Hello HelloHelloHelloHello

Course Code: COMP 241 9


AI Lab Manual

(b) Write a python program to implement list operations (add, append, extend &
delete)

Code:
myList = ["Earth", "revolves", "around", "Sun"]

print(myList)

print(len(myList))

print(myList[0])

print(myList[3])

#Slice elements from a list

print(myList[1:3])

#Use negative index

print(myList[-1])

#print(myList[4])

#add element to a list

myList.insert(0,"The")

print(myList)

print(len(myList))

myList.insert(4,"the")

print(myList)

#append an element to a list

myList.append("continuously")

print(myList)

print(len(myList))

#When use extend the argument should be another list

#the elements of that list will be added

#to the current list as individual elements

myList.extend(["for", "sure"])

Course Code: COMP 241 10


AI Lab Manual

print(myList)

print(len(myList))

#you can append a sublist to the current list using append

myList.append(["The","earth","rotates"])

print(myList)

print(len(myList))

#delete a element in the list using element

myList.remove("The")

#delete a element in the list using index

myList.remove(myList[3])

print(myList)

Output

['Earth', 'revolves', 'around', 'Sun']

Earth

Sun

['revolves', 'around']

Sun

['The', 'Earth', 'revolves', 'around', 'Sun']

['The', 'Earth', 'revolves', 'around', 'the', 'Sun']

['The', 'Earth', 'revolves', 'around', 'the', 'Sun', 'continuously']

['The', 'Earth', 'revolves', 'around', 'the', 'Sun', 'continuously', 'for', 'sure']

['The', 'Earth', 'revolves', 'around', 'the', 'Sun', 'continuously', 'for', 'sure', ['The',
'earth', 'rotates']]

Course Code: COMP 241 11


AI Lab Manual

10

['Earth', 'revolves', 'around', 'Sun', 'continuously', 'for', 'sure', ['The', 'earth', 'rotates']]

4 (a). Write a python program to Illustrate Different Set Operations?

Code:
# Program to perform different set operations like in mathematics

# define three sets

E = {0, 2, 4, 6, 8};

N = {1, 2, 3, 4, 5};

# set union

print("Union of E and N is",E | N)

# set intersection

print("Intersection of E and N is",E & N)

# set difference

print("Difference of E and N is",E - N)

# set symmetric difference

print("Symmetric difference of E and N is",E ^ N)

Output:

Union of E and N is {0, 1, 2, 3, 4, 5, 6, 8}

Intersection of E and N is {2, 4}

Difference of E and N is {0, 8, 6}

Symmetric difference of E and N is {0, 1, 3, 5, 6, 8}

(b). Write a python program to generate Calendar for the given month and
year?
Code:
# Python program to display calendar of given month of the year

# To ask month and year from the user# Python program to display calendar of given
month of the year

Course Code: COMP 241 12


AI Lab Manual

# import module
import calendar

# To ask month and year from the user


yy = int(input("Enter year: "))
mm = int(input("Enter month: "))

# display the calendar


print(calendar.month(yy, mm))
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))

# display the calendar


print(calendar.month(yy, mm))

Output:

Enter year: 2019

Enter month: 10
October 2019
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31

(c). Write a python program to implement Simple Calculator program?


Code:

# Program make a simple calculator that can add, subtract, multiply and divide
using functions

# define functions

def add(x, y):

"""This function adds two numbers"""

Course Code: COMP 241 13


AI Lab Manual

return x + y

def subtract(x, y):

""This function subtracts two numbers"""

return x - y

def multiply(x, y):

"""This function multiplies two numbers"""

return x * y

def divide(x, y):

"""This function divides two numbers"""

return x / y

# take input from the user

print("Select operation.")

print("1.Add")

print("2.Subtract")

print("3.Multiply")

print("4.Divide")

choice = input("Enter choice(1/2/3/4):")

num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))

if choice == '1':

print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':

print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':

print(num1,"*",num2,"=", multiply(num1,num2))

Course Code: COMP 241 14


AI Lab Manual

elif choice == '4':

print(num1,"/",num2,"=", divide(num1,num2))

else:

print("Invalid input")

Output:

Select operation.

1.Add

2.Subtract

3.Multiply

4.Divide

Enter choice(1/2/3/4):1

Enter first number: 21

Enter second number: 22

21 + 22 = 43

5. Write a python program to solve N Queen problem using backtracking.

Code:

# Python program to solve N Queen

# Problem using backtracking

global N

N=4

def printSolution(board):

for i in range(N):

for j in range(N):

print (board[i][j], )

print

Course Code: COMP 241 15


AI Lab Manual

# A utility function to check if a queen can

# be placed on board[row][col]. Note that this

# function is called when "col" queens are

# already placed in columns from 0 to col -1.

# So we need to check only left side for

# attacking queens

def isSafe(board, row, col):

# Check this row on left side

for i in range(col):

if board[row][i] == 1:

return False

# Check upper diagonal on left side

for i, j in zip(range(row, -1, -1), range(col, -1, -1)):

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

return False

# Check lower diagonal on left side

for i, j in zip(range(row, N, 1), range(col, -1, -1)):

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

return False

Course Code: COMP 241 16


AI Lab Manual

return True

def solveNQUtil(board, col):

# base case: If all queens are placed

# then return true

if col >= N:

return True

# Consider this column and try placing

# this queen in all rows one by one

for i in range(N):

if isSafe(board, i, col):

# Place this queen in board[i][col]

board[i][col] = 1

# recur to place rest of the queens

if solveNQUtil(board, col + 1) == True:

return True

# If placing queen in board[i][col

# doesn't lead to a solution, then

# queen from board[i][col]

board[i][col] = 0

Course Code: COMP 241 17


AI Lab Manual

# if the queen can not be placed in any row in

# this colum col then return false

return False

# This function solves the N Queen problem using

# Backtracking. It mainly uses solveNQUtil() to

# solve the problem. It returns false if queens

# cannot be placed, otherwise return true and

# placement of queens in the form of 1s.

# note that there may be more than one

# solutions, this function prints one of the

# feasible solutions.

def solveNQ():

board = [ [0, 0, 0, 0],

[0, 0, 0, 0],

[0, 0, 0, 0],

[0, 0, 0, 0]

if solveNQUtil(board, 0) == False:

print ("Solution does not exist")

return False

printSolution(board)

return True

Course Code: COMP 241 18


AI Lab Manual

# driver program to test above function

solveNQ()

Output:

runfile('C:/Users/Rajan/NQueen.py', wdir='C:/Users/Rajan')

0010

1000

0001

0100

6. Write a python program to implement Breadth first search Traversal.

Code:

"""

This file contains an implementation of breadth-first search (BFS) for

traversing a graph, and for getting the shortest path between 2 nodes

of a graph.

"""

# visits all the nodes of a graph (connected component) using BFS

def bfs_connected_component(graph, start):

# keep track of all visited nodes

explored = []

# keep track of nodes to be checked

queue = [start]

# keep looping until there are nodes still to be checked

while queue:

# pop shallowest node (first node) from queue

node = queue.pop(0)
Course Code: COMP 241 19
AI Lab Manual

if node not in explored:

# add node to list of checked nodes

explored.append(node)

neighbours = graph[node]
# add neighbours of node to queue

for neighbour in neighbours:

queue.append(neighbour)

return explored

# finds shortest path between 2 nodes of a graph using BFS

def bfs_shortest_path(graph, start, goal):

# keep track of explored nodes

explored = []

# keep track of all the paths to be checked

queue = [[start]]

# return path if start is goal

if start == goal:

return "That was easy! Start = goal"

# keeps looping until all possible paths have been checked

while queue:

# pop the first path from the queue

path = queue.pop(0)

# get the last node from the path

node = path[-1]

if node not in explored:

neighbours = graph[node]

# go through all neighbour nodes, construct a new path and

# push it into the queue

for neighbour in neighbours:


Course Code: COMP 241 20
AI Lab Manual

new_path = list(path)

new_path.append(neighbour)

queue.append(new_path)

# return path if neighbour is goal

if neighbour == goal:

return new_path

# mark node as explored

explored.append(node)

# in case there's no path between the 2 nodes

return "So sorry, but a connecting path doesn't exist :("

if name == ' main ':

# sample graph represented by a dictionary

graph = {'A': ['B', 'C'],

'B': ['A','D'],

'C': ['A','E','F'],

'D': ['B'],

'E': ['C',],

'F': ['C'],

# A

# /\

# / \

# B C

# / /\

# / / \

# D E F

Course Code: COMP 241 21


AI Lab Manual

print("\nHere's the nodes of the graph visited by "

"breadth-first search, starting from node 'A': ",

bfs_connected_component(graph, 'A'))

print("\nHere's the shortest path between nodes 'D' and 'F':",

bfs_shortest_path(graph, 'D', 'F'))

OUTPUT: -

HERE'S THE NODES OF THE GRAPH VISITED BY BREADTH-FIRST SEARCH,


STARTING FROM NODE 'A': ['A', 'B', 'C', 'D', 'E', 'F']

HERE'S THE SHORTEST PATH BETWEEN NODES 'D' AND 'F': ['D', 'B', 'A', 'C', 'F']

7. Consider this graph, and implement the code in python for Depth first Search Traversal.

# Using a Python dictionary to act as an adjacency list


graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}

visited = [] # Array to keep track of visited nodes.

def dfs(visited, graph, node):


if node not in visited:
print (node),
visited.append(node)
for neighbour in graph[node]:
Course Code: COMP 241 22
AI Lab Manual

dfs(visited, graph, neighbour)

# Driver Code
dfs(visited, graph, 'A')

Output: runfile('C:/Users/jose_/.spyder-py3/Depth first search.py', wdir='C:/Users/jose_/.spyder-py3')


A
B
D
E
F
C

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


A Water Jug Problem: You are given two jugs, a 4-gallon one and a 3-gallon one, a
pump which has unlimited water which you can use to fill the jug, and the ground on
which water may be poured. Neither jug has any measuring markings on it. How can
you get exactly 2 gallons of water in the 4-gallon jug?

Let X represent the content of the water in 4-gallon jug.


Let Y represent the content of the water in 3-gallon jug.

Write a program in python to define a set of operators (Rules) that will take us from
one state to another:

Start from initial state (X=0, Y=0)


Reach any of the Goal states
(X=2, Y=0)
(X=2, Y=1)
(X=2, Y=2)
(X=2, Y=3)
Find the minimum number of steps to reach any the above mentioned goal states.

Code:

print("Water Jug Problem")


x=int(input("Enter X:"))
y=int(input("Enter Y:"))
while True:

rno=int(input("Enter the Rule No"))

if rno==1:
if x<4:x=4

if rno==2:

Course Code: COMP 241 23


AI Lab Manual

if y<3:y=3

if rno==5:
if x>0:x=0

if rno==6:
if y>0:y=0

if rno==7:
if x+y>= 4 and y>0:x,y=4,y-(4-x)

if rno==8:
if x+y>=3 and x>0:x,y=x-(3-y),3

if rno==9:
if x+y<=4 and y>0:x,y=x+y,0

if rno==10:
if x+y<=3 and x>0:x,y=0,x+y

print("X =" ,x)


print("Y =" ,y)
if (x==2):
print(" The result is a Goal state")
break

Output:

Water Jug Problem


Enter X:0
Enter Y:0
Enter the Rule No2
X=0
Y=3
Enter the Rule No9
X=3
Y=0
Enter the Rule No2
X=3
Y=3
Enter the Rule No7
X=4
Y=2
Enter the Rule No5
X=0
Y=2

Course Code: COMP 241 24


AI Lab Manual

Enter the Rule No9


X=2
Y=0
The result is a Goal state.

9. (a) Write a python program to remove punctuations from the given string?
Code:
# define punctuation

punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

my_str = "Hello!!!, he said ---and went."

# To take input from the user

# my_str = input("Enter a string: ")

# remove punctuation from the string

no_punct = ""

for char in my_str:

if char not in punctuations:

no_punct = no_punct + char

# display the unpunctuated string

print(no_punct)

Output:

Hello he said and went

(b) Write a python program to sort the sentence in alphabetical order?


Code:
# Program to sort alphabetically the words form a string provided by the user

# change this value for a different result

my_str = "Hello this Is an Example With cased letters"

# uncomment to take input from the user

#my_str = input("Enter a string: ")

# breakdown the string into a list of words


words = my_str.split()
Course Code: COMP 241 25
AI Lab Manual

#print(words)

# sort the list

words.sort()

# display the sorted words

print("The sorted words are:")

for word in words:

print(word)

Output:

The sorted words are:

Example

Hello

Is

With

an

cased

letters

this

10. Write a program to implement Hangman game using


python. Description:

Hangman is a classic word-guessing game. The user should guess the word correctly by
entering alphabets of the user choice. The Program will get input as single alphabet from the
user and it will matchmaking with the alphabets in the original word. If the user given alphabet
matches with the alphabet from the original word then user must guess the remaining alphabets.
Once the user successfully found the word he will be declared as winner otherwise user lose
the game.

Python Code:

def getAvailableLetters(lettersGuessed):

'''

lettersGuessed: list, what letters have been guessed so far

Course Code: COMP 241 26


AI Lab Manual

returns: string, comprised of letters that represents what letters have not

yet been guessed.

'''

import string

fullstring = string.ascii_lowercase

lettersLeft = ''

for letter in fullstring:

if letter not in lettersGuessed:

lettersLeft = lettersLeft + letter

return lettersLeft

def getGuessedWord(secretWord, lettersGuessed):

'''

secretWord: string, the word the user is guessing

lettersGuessed: list, what letters have been guessed so far

returns: string, comprised of letters and underscores that represents

what letters in secretWord have been guessed so far.

''

wordGuessed = ''

for letter in secretWord:

if letter in lettersGuessed:

wordGuessed = wordGuessed + letter

else:

wordGuessed = wordGuessed + '_ '

return wordGuessed

def isWordGuessed(secretWord, lettersGuessed):

Course Code: COMP 241 27


AI Lab Manual

'''

secretWord: string, the word the user is guessing

lettersGuessed: list, what letters have been guessed so far

returns: boolean, True if all the letters of secretWord are in lettersGuessed;

False otherwise

'''

numCorrect = 0

for letter in secretWord:

if letter in lettersGuessed:

numCorrect += 1

else:

return False

return True

def hangman(secretWord):

guessesLeft = 8

lettersGuessed =[]

print('Welcome to the game Hangman!')


print('I am thinking of a word that is ' + str(len(secretWord)) + ' letters long.' )

print(' ---------- ')

while guessesLeft > 0:

if isWordGuessed(secretWord, lettersGuessed):

return print('Congratulations, you won!')

print('You have ' + str(guessesLeft) + ' guesses left.')

print('Available Letters: ' + getAvailableLetters(lettersGuessed))

user_input = input('Please guess a letter: ')

user_input = str(user_input)

user_input = user_input.lower()

if user_input not in lettersGuessed:


Course Code: COMP 241 28
AI Lab Manual

lettersGuessed.append(user_input)

if user_input in secretWord:

print("Good guess: " + getGuessedWord(secretWord, lettersGuessed))

print(' ---------- ')

else:

print("Oops! That letter is not in my word: " + getGuessedWord(secretWord,


lettersGuessed))

print(' ---------- ')

guessesLeft -= 1

else:

print("Oops! You've already guessed that letter: " + getGuessedWord(secretWord,


lettersGuessed))

print(' ---------- ')

return print("Sorry, you ran out of guesses. The word was " + str(secretWord))

hangman('apple')

Output:

Welcome to the game Hangman!

I am thinking of a word that is 5 letters long.

-----------

You have 8 guesses left.

Available Letters: abcdefghijklmnopqrstuvwxyz

Please guess a letter: a

Good guess: a_ _ _ _

-----------

You have 8 guesses left.

Available Letters: bcdefghijklmnopqrstuvwxyz

Please guess a letter: p

Good guess: app_ _

Course Code: COMP 241 29


AI Lab Manual

-----------

You have 8 guesses left.

Available Letters: bcdefghijklmnoqrstuvwxyz

Please guess a letter: p

Oops! You've already guessed that letter: app_ _

-----------

You have 8 guesses left.

Available Letters: bcdefghijklmnoqrstuvwxyz

Please guess a letter: l

Good guess: appl_

-----------

You have 8 guesses left.

Available Letters: bcdefghijkmnoqrstuvwxyz

Please guess a letter: e

Good guess: apple

-----------

Congratulations, you won!

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

Code:

import nltk

from nltk.corpus import stopwords

f1 = open("file1.txt","r")

f2 = open("file2.txt","w")

stop = stopwords.words('english')

for line in f1:

Course Code: COMP 241 30


AI Lab Manual

w = line.split(" ")

for word in w:

if word not in stop:

f2.write(word)

f2.write(" ")

f1.close()

f2.close()

Output:

Course Code: COMP 241 31


AI Lab Manual

(b) Write a python program to implement stemming for a given sentence using
NLTK?
Code:
from nltk.stem import PorterStemmer

from nltk.tokenize import word_tokenize

ps= PorterStemmer()

example_words = [" python,pythonly,phythoner,pythonly"]

for w in example_words:

print(ps.stem(w))

Output:

python,pythonly,phythoner,pythonli

(c) Write a python program to POS (Parts of Speech) tagging for the give sentence
using NLTK?
Code:

import nltk

text = nltk.word_tokenize('ive into NLTK: Part-of-speech tagging and POS Tagger')

pos = nltk.pos_tag(text)

print(text)

print(pos)

Course Code: COMP 241 32


AI Lab Manual

Output:

['ive', 'into', 'NLTK', ':', 'Part-of-speech', 'tagging', 'and', 'POS', 'Tagger']

[('ive', 'JJ'), ('into', 'IN'), ('NLTK', 'NNP'), (':', ':'), ('Part-of-speech', 'JJ'), ('tagging',
'NN'), ('and', 'CC'), ('POS', 'NNP'), ('Tagger', 'NNP')]

12. (a) Write a python program to implement Lemmatization using NLTK?

Code:
from nltk.stem import WordNetLemmatizer

lemmatizer = WordNetLemmatizer()

print(lemmatizer.lemmatize("cats"))

print(lemmatizer.lemmatize("cacti"))

print(lemmatizer.lemmatize("geese"))

print(lemmatizer.lemmatize("rocks"))

print(lemmatizer.lemmatize("pyth"))

print(lemmatizer.lemmatize("cats"))

Output:

cat

cactus

goose

rock

pyth

cat

(b) Write a python program to for Text Classification for the give sentence using
NLTK?
Code:

import nltk

import random

Course Code: COMP 241 33


AI Lab Manual

from nltk.corpus import movie_reviews

documents = [(list(movie_reviews.words(fileid)), category)

for category in movie_reviews.categories()

for fileid in movie_reviews.fileids(category)]

random.shuffle(documents)

print(documents[1])

all_words = []

for w in movie_reviews.words():

all_words.append(w.lower())

all_words = nltk.FreqDist(all_words)

print(all_words.most_common(15))

print(all_words["stupid"])

Output:

([u'making', u'your', u'first', u'feature', u'film', u'ain', u"'", u't', u'easy', u'.', u'assemble',
u'a', u'decent', u',', u'if', u'not', u',', u'strong', u'cast', u',', u'as', u'writer', u'/', u'director',
u'robert', u'moresco', u'has', u'done', u'with', u'one', u'eyed', u'king', u',', u'and', u'you',
u"'", u're', u'already', u'ahead', u'of', u'the', u'game', u'.', u'but', u'rehash', u'old', u'plot',
u'lines', u',', u'tired', u'dialogue', u',', u'and', u'standard', u'clich', u'?', u's', u',', u'and',
u'a', u'well', u'-', u'intentioned', u'effort', u'such', u'as', u'this', u'one', u'could',
u'jeopardize', u'your', u'chance', u'at', u'a', u'second', u'feature', u'film', u'.', u'how',
u'many', u'more', u'movies', u'do', u'we', u'need', u'about', u'a', u'rough',
u'neighborhood', u'full', u'of', u'lifelong', u'friends', u'hopelessly', u'turned', u'to',
u'crime', u'or', u'worse', u'?', u'the', u'enormous', u'catalog', u'of', u'such', u'movies',
u'might', u'dissuade', u'a', u'filmmaker', u'from', u'making', u'yet', u'another', u',', u'but',
u'here', u'we', u'have', u'it', u'.', u'again', u'.', u'five', u'irish', u'kids', u'in', u'nyc',
u"'", u's', u'hell', u"'", u's', u'kitchen', u'make', u'an', u'overemotional', u'pact', u'over',
u'some', u'stolen', u'rings', u'on', u'an', u'anonymous', , u'and', u'slow', u'motion', u'.',
u'in', u'the', u'film', u"'", u's', u'first', u'scene', u'.', , '], u'neg')

Course Code: COMP 241 34

You might also like