Lab Manual - Data Mining

You might also like

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

Data Mining Lab

Code: PCC- DS492

Laboratory Instructor’s Manual

Last Received
2024

Department of Computer Science & Engineering (Data Science)

Techno Main Salt Lake


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

GENERAL INSTRUCTIONS FOR STUDENTS

1. Do not enter the Laboratory without prior permission.

2. Switch off your mobile phones during Lab class and maintain silence.

3. Save your files only on the specific destination folders as instructed.

4. Do not play games, watch movies, chat, or listen to music during the class.

5. Do not change desktop settings, screen saver, or any other system settings.

6. Do not use any external storage device without prior permission.

7. Do not install any software without prior permission.

8. Do not browse any restricted, illegal, or spam sites.

GENERAL ADDRESS FOR LABORATORY TEACHERS

1. Submission of documented lab reports related to completed lab assignments should be done

during the following lab session.

2. The promptness of submission should be encouraged by way of marking and evaluation

patterns as reflected in the lab rubric which eventually will benefit the students.

DEPT. OF CSE (AIML & DATA SCIENCE) 2


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

Program Outcomes (PO)

PO1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and engineering specialization to the solution of complex engineering problems.

PO2. Problem analysis: Identify, formulate, research literature, and analyze engineering problems to
arrive at substantiated conclusions using the first principles of mathematics, natural, and engineering
sciences.

PO3. Design/Development of solutions: Design solutions for complex engineering problems and design
system components, and processes to meet the specifications with consideration for the public health and
safety and the cultural societal, and environmental considerations.

PO4. Conduct investigations of complex problems: Use research-based knowledge including design of
experiments, analysis and interpretation of data, and synthesis of the information to provide valid
conclusions.

PO5. Modern and usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activities with an
understanding of the limitations.

PO6. The engineer and society: Apply reasoning informed by the contextual knowledge to access
societal, health, safety, legal, and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.

PO7. Environment and sustainability: Understand the impact of professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of and need for sustainable
development.

PO8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.

PO9. Individual and team work: Function effectively as an individual, and as a member or leader in
teams, and in multidisciplinary settings.

PO10. Communications: Communicate effectively with the engineering community and with the society
at large. Be able to comprehend and write effective reports and documentation. Make effective presentations
and give and receive clear instructions.

PO11. Project management and finance: Demonstrate knowledge and understanding of engineering and
management principles and apply these to one’s work, as a member and leader in a team. Manage projects
in multidisciplinary environments.

PO12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and lifelong learning in the broadest context of technological change.

DEPT. OF CSE (AIML & DATA SCIENCE) 3


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

Program Specific Outcomes (PSO)

PSO1: Ability to develop solutions for scientific, analytical, and research-oriented problems in the area of
Computer Science and Engineering (Data Science).

PSO2: Ability to apply suitable programming skills integrated with professional competence to develop
applications catering to the industrial and societal needs in the field of Computer Science and Engineering
(Data Science) and its allied areas.

DEPT. OF CSE (AIML & DATA SCIENCE) 4


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

NAME OF THE PROGRAM: CSE (Data Science) DEGREE: B.Tech


COURSE NAME: Data Mining Lab SEMESTER:
COURSE CODE: PCC- DS492 COURSE CREDIT: 2
COURSE TYPE: LAB CONTACT HOURS: 4P

SYLLABUS

Manipulating strings, Processing Files, Manipulating Lists, Lists and Strings, Dictionary, counting
with Dictionaries, Dictionaries and Files, Tuples, Tuples and Sorting, Regular Expressions,
Networked programs, Sockets and Applications, parsing HTML with Beautiful soup, parsing XML
by Python, REST, JSON and APIs, extracting data from JSON, using database by python, Object-
oriented python, Geocoding, Page rank and web searching, Gm, lane.

DEPT. OF CSE (AIML & DATA SCIENCE) 5


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

NAME OF THE PROGRAM: DEGREE:


COURSE NAME: SEMESTER:
COURSE CODE: COURSE CREDIT: 2
COURSE TYPE: LAB CONTACT HOURS: 4P

Course Outcomes (COs)

After this course, students will be able to:

DEPT. OF CSE (AIML & DATA SCIENCE) 6


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

NAME OF THE PROGRAM: CSE (Data Science) DEGREE: B.Tech


COURSE NAME: Data Mining Lab SEMESTER: 4th
COURSE CODE: PCC- DS492 COURSE CREDIT: 2
COURSE TYPE: LAB CONTACT HOURS: 4P

Exp. No. List of Experiments Week

Basic recap of list, string, and tuple dictionary using python


1. Week 1

2. String and File operations Week 2

3.

4.

5.

6.

7.

8.

DEPT. OF CSE (AIML & DATA SCIENCE) 7


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

Experiment No: 1
Experiment: Basic recap of list, string, and tuple dictionary using python

Overview Strings, Lists, Dictionaries, Tuples

The four main types of objects you will work with are strings, lists, dictionaries, and tuples.
Knowing how to manipulate these objects is incredibly important in Python. Before discussing
each object in detail, I wanted to give an overview of the four objects.

string list dictionary tuple


Immutable or mutable? immutable mutable mutable immutable
Indexed by? integers integers any immutable type integers
operators + and * ? Yes Yes No Yes
in operator? Yes Yes Yes Yes
apply methods? Yes Yes Yes No

Definitions:

• A string is a sequence of characters.


• A list is a sequence of values which can be characters, integers, or even another list
(referred to as a nested list).
• A dictionary is a more general version of a list and is made up of a set of keys and
values where there is a mapping between a given key and its corresponding value.
There is no order to the set of keys and values.
• A tuple is a sequence of values (any type) which makes them similar to lists, but the
difference is they are immutable.

Immutable vs mutable:

• Strings are immutable. When using strings, bracket operators cannot be used on the
left side of an assignment to change that string.
• Lists are mutable. Unlike strings, you can use the bracket operator on the left side of
the assignment to change an element in a given list.
• Dictionaries are mutable. You can modify any item (key-value pair) in a dictionary
using the bracket operator on the left side of the assignment.
• Tuples are immutable. You can extract elements, but you cannot modify elements of a
tuple on the left side of the assignment operator.

The in operator:

The in operator (and not in operator) is a boolean operator that takes in two arguments that
determine if the first argument is a substring or an element of the second argument.

• When comparing two strings, the operator searches if the first string appears as a
substring in the second and returns a True or False.
• If the second argument is a list, the operator can take in two a string and a list to see if
the string appears as one of the elements in the list and returns a True or False.

DEPT. OF CSE (AIML & DATA SCIENCE) 8


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

The len function:

The function len() can be used to:

• Calculate the length of a string


• Calculate the number of elements in a list
• Calculate the number of items (key-value pairs) in a dictionary
• Calculate the number of elements in the tuple

Methods for each type of object (dot notation)

For strings, lists, and dictionaries, there are a set of methods you can use to manipulate the
objects. Because tuples are immutable, there are no methods to modify the objects. In general,
the notation for methods is the dot notation. The syntax is the name of the objects followed
by a dot (or period) followed by the method's name.

x = "Hello Boston!"
x.split()

Here we use the method split() applied to a string (making this a string method). The method
splits the string at a given delimiter (the white space “ “).

When to use which object?

In the subsequent pages, I will compare and contrast the similarities and differences of strings,
lists, dictionaries, and tuples in greater detail. In general, lists are more common than tuples
(mostly because they are mutable), but there are a few reasons why tuples may be preferable:

1. In some contexts, like a return statement, it is syntactically simpler to create a tuple than
a list. In other contexts, you might prefer a list.
2. If you want to use a sequence as a dictionary key, use an immutable type like a tuple or
string.
3. If we pass a sequence as an argument to a function, using tuples reduces the potential
for unexpected behaviour due to aliasing.

Again, because tuples are immutable, they do not provide methods like split().

Q1. Write a Python script that prints prime numbers less than 20.

Ans:

print("Prime numbers between 1 and 20 are:")


ulmt=20;
for num in range(ulmt):
# prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)

DEPT. OF CSE (AIML & DATA SCIENCE) 9


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

Q2. Write a program to create, concatenate, and print a string and access a substring from a
given string.
Ans:
# Create a string
user_str1 = input('Enter a string: ')
# Concatenate strings
user_str2 = user_str1 + 'World!'
# Print the concatenated string
print('Concatenated String:', user_str2)
# Access substring
start_index = int(input('Enter the starting index for the substring: '))
end_index = int(input('Enter the ending index for the substring: '))
user_substring = user_str2[start_index:end_index]
# Print the substring
print('Substring:', user_substring)

Q3. write a program to create, append, and remove lists in Python.


Ans:

# Create an empty list


user_list = []
# Add elements to the list
while True:
user_input = input('Enter an element to add (or type \'done\' to finish): ')
if user_input.lower() == 'done':
break
user_list.append(user_input)
# Print the list
print('List after adding elements:', user_list)
# Remove an element from the list
if len(user_list) > 0:
remove_index = int(input('Enter the index of the element to remove: '))
if 0 <= remove_index < len(user_list):
removed_element = user_list.pop(remove_index)
print('Removed element:', removed_element)
print('List after removal:', user_list)
else:
print('Invalid index. No element removed.')
else:
print('List is empty. No element removed.')

Q4. Write a program to demonstrate working with tuples in Python.


Ans:

# Create an empty tuple


user_tuple = ()
# Add elements to the tuple
while True:
user_input = input('Enter an element to add (or type \'done\' to finish): ')
if user_input.lower() == 'done':
break
user_tuple += (user_input,)
# Print the tuple

DEPT. OF CSE (AIML & DATA SCIENCE) 10


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

print('Tuple after adding elements:', user_tuple)


# Access elements from the tuple
if len(user_tuple) > 0:
index = int(input('Enter the index of the element to access: '))
if 0 <= index < len(user_tuple):
accessed_element = user_tuple[index]
print('Accessed element:', accessed_element)
else:
print('Invalid index. No element accessed.')
else:
print('Tuple is empty. No element accessed.')

Q5. Write a program to demonstrate working with dictionaries in Python.


Ans:
# Create an empty dictionary
user_dict = {}

# Add key-value pairs to the dictionary


while True:
user_key = input('Enter a key (or type \'done\' to finish): ')
if user_key.lower() == 'done':
break
user_value = input(f'Enter a value for the key \'{user_key}\': ')
user_dict[user_key] = user_value

# Print the dictionary


print('Dictionary after adding key-value pairs:', user_dict)

# Access a value from the dictionary


if len(user_dict) > 0:
user_key_to_access = input('Enter a key to access its value: ')
if user_key_to_access in user_dict:
accessed_value = user_dict[user_key_to_access]
print('Accessed value:', accessed_value)
else:
print('Key not found. No value accessed.')
else:
print('Dictionary is empty. No value accessed.')

DEPT. OF CSE (AIML & DATA SCIENCE) 11


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

Experiment No: 2
Experiment: String and File operations

Indexing means referring to an element of an iterable by its position within the iterable. Each
of a string’s characters corresponds to an index number and each character can be accessed
using its index number. We can access characters in a String in Two ways:

1. Accessing Characters by Positive Index Number


2. Accessing Characters by Negative Index Number

Accessing Characters by Positive Index Number: In this type of Indexing, we pass a Positive
index(which we want to access) in square brackets. The index number starts from index number
0 (which denotes the first character of a string)

# Declaring the string


str = "Techno Main Saltlake"
# accessing the character of str at 0th index
print(str[0])
# accessing the character of str at 7th index
print(str[7])
# accessing the character of str at 10th index
print(str[10])

Output:
T
M
n
=== Code Execution Successful ===

Accessing Characters by Negative Index Number: In this type of Indexing, we pass the
Negative index(which we want to access) in square brackets. Here the index number starts from
index number -1 (which denotes the last character of a string). Example 2 (Negative Indexing):

# Declaring the string


str = "Techno Main Saltlake"
# accessing the character of str at -1th index
print(str[-1])
# accessing the character of str at -6th index
print(str[-7])
# accessing the character of str at -10th index
print(str[-10])

Output:
e
a
n

=== Code Execution Successful ===

DEPT. OF CSE (AIML & DATA SCIENCE) 12


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

Slicing Operator

The slice() function returns a slice object.

A slice object is used to specify how to slice a sequence. We can specify where to start the
slicing, and where to end. We can also specify the step, that allows us to e.g. slice only every
other item.

a = ("Techno Main Saltlake")

x = slice(0,10,2)

print(a[x])

Output:

Tcn a

Python String Methods (strip, lstrip, rstrip)

1. strip():- This method is used to delete all the leading and trailing characters
mentioned in its argument.
2. 2. lstrip():- This method is used to delete all the leading characters mentioned in its
argument.
3. 3. rstrip():- This method is used to delete all the trailing characters mentioned in its
argument.

# Python code to demonstrate working of


# strip(), lstrip() and rstrip()
str = "---Techno Main Salt lake---"

# using strip() to delete all '-'


print ( " String after stripping all '-' is : ", end="")
print ( str.strip('-') )

# using lstrip() to delete all trailing '-'


print ( " String after stripping all leading '-' is : ", end="")
print ( str.lstrip('-') )

# using rstrip() to delete all leading '-'


print ( " String after stripping all trailing '-' is : ", end="")
print ( str.rstrip('-') )

Output:

String after stripping all '-' is : Techno Main Salt lake


String after stripping all leading '-' is : Techno Main Salt lake---
String after stripping all trailing '-' is : ---Techno Main Salt lake

Python String Methods (replace()):

DEPT. OF CSE (AIML & DATA SCIENCE) 13


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

replace():- This function is used to replace the substring with a new substring in the string. This
function has 3 arguments. The string to replace, new string which would replace, and max value
denoting the limit to replace action ( by default unlimited ).

# Python code to demonstrate the working of


# replace()

str = "TMSL is the best"

str1 = "TMSL"
str2 = "Techno Main Salt Lake"

# using replace() to replace str2 with str1 in str


# only changes 2 occurrences
print ("The string after replacing strings is : ", end="")
print (str.replace( str1, str2, 2))

Output:
The string after replacing strings is : Techno Main Salt Lake is the best

Python String Methods (find, rfind, startwith, endwith, lower, upper, swapcase & title):

find(“string”, beg, end):- This function is used to find the position of the substring within a
string.It takes 3 arguments, substring, starting index( by default 0), and ending index( by
default string length).

• It returns “-1 ” if the string is not found in a given range.


• It returns the first occurrence of the string if found.

rfind(“string”, beg, end):- This function has a similar working as find(), but it returns the
position of the last occurrence of the string.

# Python code to demonstrate working of


# find() and rfind()
str = "Techno Main Salt Lake is the best in Salt Lake, Kolkata"
str2 = "Lake"

# using find() to find first occurrence of str2


# returns 8
print ("The first occurrence of str2 is at : ", end="")
print (str.find( str2, 4) )

# using rfind() to find last occurrence of str2


# returns 21
print ("The last occurrence of str2 is at : ", end="")
print ( str.rfind( str2, 4) )

Output:
The first occurrence of str2 is at : 17
The last occurrence of str2 is at : 42

DEPT. OF CSE (AIML & DATA SCIENCE) 14


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

startswith(“string”, beg, end) :- The purpose of this function is to return true if the function begins
with the mentioned string(prefix) else return false.

endswith(“string”, beg, end) :- The purpose of this function is to return true if the function ends
with mentioned string(suffix) else return false.

txt = "Hello, welcome to my world."


x = txt.startswith("Hello")
print(x)

x1= txt.endswith("Hello")
print(x1)

Output:
True
False

lower():- This function returns the new string with all the letters converted into its
lowercase.
upper():- This function returns the new string with all the letters converted into its upper
case.
swapcase():- This function is used to swap the cases of string i.e upper case is converted to
lower case and vice versa.
title():- This function converts the string to its title case i.e the first letter of every word of
string is upper cased and else all are lower cased.

# Python code to demonstrate working of


# upper(), lower(), swapcase() and title()
str = "Techno Main Salt Lake"

# Converting the string into its lowercase


str1 = str.lower();
print (" The lower case converted string is : " + str1)

# Converting the string into its upper case


str2 = str.upper();
print (" The upper case converted string is : " + str2)

# Converting the string into its swapped case


str3 = str.swapcase();
print (" The swap case converted string is : " + str3)

# Converting the string into its title case


str4 = str.title();
print (" The title case converted string is : " + str4)

Output:
The lower case converted string is : techno main salt lake
The upper case converted string is : TECHNO MAIN SALT LAKE
The swap case converted string is : tECHNO mAIN sALT lAKE
The title case converted string is : Techno Main Salt Lake

DEPT. OF CSE (AIML & DATA SCIENCE) 15


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

Python String split() method splits a string into a list of strings after breaking the given string
by the specified separator.
text = 'Techno Main Salt Lake'

# Splits at space
print(text.split())

word = 'Techno, Main, Salt, Lake'

# Splits at ','
print(word.split(','))

word = 'Techno: Main: Salt: Lake'

# Splitting at ':'
print(word.split(':'))

word = 'CatBatSatFatOr'

# Splitting at t
print(word.split('t'))

Output:
['Techno', 'Main', 'Salt', 'Lake']
['Techno', ' Main', ' Salt', ' Lake']
['Techno', ' Main', ' Salt', ' Lake']
['Ca', 'Ba', 'Sa', 'Fa', 'Or']

In Python, we can use the join() method with different types of iterables such as Lists,
Tuple, String, Dictionary, and Sets. Let’s understand them one by one with the help of
examples.
str = '-'.join('TMSL')
print(str)

Output:
T-M-S-L

Python String index() Method allows a user to find the index of the first occurrence of an
existing substring inside a given string in Python.

# initializing target string


ch = "TMSL is the best."

# initializing argument string


ch1 = "best"

# using index() to find the position of "best"


# starting from 2nd index
# prints 8
pos = ch.index(ch1,2)

DEPT. OF CSE (AIML & DATA SCIENCE) 16


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

print("The first position of geeks after 2nd index : ",end="")


print(pos)

Output:
The first position of geeks after 2nd index : 12

Python String rindex() method returns the highest index of the substring inside the string if
the substring is found. Otherwise, it raises ValueError.

text = 'TMSL is the best.'

result = text.rindex('best')
print("Substring 'best':", result)

Output:
Substring 'best': 12

The string len() function is a built-in function in Python that is used to find the length of the
string. You can know the number of characters in a string using this function.

string = "TMSL is the best."


print(len(string))

Output:
17

String count() function is an inbuilt function in Python programming language that returns
the number of occurrences of a substring in the given string. It is a very useful string function
that can be used for string analysis.

#initializing a string
my_string = "Techno Main Salt Lake"
#using string count() method
char_count = my_string.count('a')
#printing the result
print(char_count)

Output:
3

Python String capitalize() method returns a copy of the original string and converts the first
character of the string to a capital (uppercase) letter while making all other characters in the
string lowercase letters.

# initializing a string
name = "techno main salt lake"
#using capitalize function
print(name.capitalize())

Output: Techno main salt lake

DEPT. OF CSE (AIML & DATA SCIENCE) 17


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

Experiment: Read and Write operations on a file.

File Access Modes

Access modes govern the type of operations possible in the opened file. It refers to how the file
will be used once its opened. These modes also define the location of the File Handle in the
file. The file handle is like a cursor, which defines from where the data has to be read or written
in the file and we can get Python output in text file.

There are 6 access modes in Python:

• Read Only (‘r’)

• Read and Write (‘r+’)

• Write Only (‘w’)

• Write and Read (‘w+’)

• Append Only (‘a’)

• Append and Read (‘a+’)

Read Only (‘r’): Open text file for reading. The handle is positioned at the beginning of the
file. If the file does not exist, raises the I/O error. This is also the default mode in which a file
is opened.

Read and Write (‘r+’): Open the file for reading and writing. The handle is positioned at the
beginning of the file. Raises I/O error if the file does not exist.

Write Only (‘w’): Open the file for writing. For the existing files, the data is truncated and
over-written. The handle is positioned at the beginning of the file. Creates the file if the file
does not exist.

Write and Read (‘w+’): Open the file for reading and writing. For an existing file, data is
truncated and over-written. The handle is positioned at the beginning of the file.

Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The handle
is positioned at the end of the file. The data being written will be inserted at the end, after the
existing data.

Append and Read (‘a+’): Open the file for reading and writing. The file is created if it does
not exist. The handle is positioned at the end of the file. The data being written will be inserted
at the end, after the existing data.

DEPT. OF CSE (AIML & DATA SCIENCE) 18


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

Q1. Python program to perform read and write operations on a file.


Ans:
# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

# \n is placed to indicate EOL (End of Line)


file1.write("Hello \n")
file1.writelines(L)
file1.close() # to change file access modes

file1 = open("myfile.txt", "r+")

print("Output of Read function is ")


print(file1.read())
print()

# seek(n) takes the file handle to the nth


# byte from the beginning.
file1.seek(0)

print("Output of Readline function is ")


print(file1.readline())
print()

file1.seek(0)

# To show difference between read and readline


print("Output of Read(9) function is ")
print(file1.read(9))
print()

file1.seek(0)

print("Output of Readline(9) function is ")


print(file1.readline(9))

file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()

Output:

Output of Read function is


Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Read(9) function is

DEPT. OF CSE (AIML & DATA SCIENCE) 19


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

Hello
Th
Output of Readline(9) function is
Hello
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

Q2. Python program to copy the contents of a file to another file.


Ans:

with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)

Output:

Case 1:
Contents of file(test.txt):
Hello world

Output(out.text):
Hello world

Case 2:
Contents of file(test.txt):
TMSL

Output(out.text):
TMSL

Q3. Python program to count frequency of characters in a given file.


Ans:

# Python3 code to demonstrate each occurrence frequency using


# collections.Counter()
from collections import Counter

# initializing string
test_str = "Techno Main SaltLake"

# using collections.Counter() to get


# count of each element in string
res = Counter(test_str)

# printing result
print("Count of all characters in GeeksforGeeks is :\n "
+ str(res))

Output:

Count of all characters in is Techno Main SaltLake:


Counter({'a': 3, 'e': 2, 'n': 2, ' ': 2, 'T': 1, 'c': 1, 'h': 1, 'o': 1, 'M': 1, 'i': 1, 'S': 1, 'l': 1, 't': 1, 'L':
1, 'k': 1})

=== Code Execution Successful ===

DEPT. OF CSE (AIML & DATA SCIENCE) 20


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

Q4. Python program to print each line of a file in reverse order.


Ans:

# Read the input file line by line


with open("file.txt", "r") as myfile:
data = myfile.readlines()

# Reverse the order of lines


reversed_lines = data[::-1]

# Write the reversed lines to an output file


with open("output2.txt", "w") as f2:
f2.writelines(reversed_lines)

Q5.

Ans:
# Function to count number of characters, words, spaces and lines in a file
def counter(fname):

# variable to store total word count


num_words = 0

# variable to store total line count


num_lines = 0

# variable to store total character count


num_charc = 0

# opening file using with() method


# so that file gets closed
# after completion of work
with open(fname, 'r') as f:

# loop to iterate file


# line by line
for line in f:

# incrementing value of num_lines with each


# iteration of loop to store total line count
num_lines += 1

# declaring a variable word and assigning its value as Y


# because every file is supposed to start with a word or a character
word = 'Y'

# loop to iterate every


# line letter by letter
for letter in line:

# condition to check that the encountered character


# is not white space and a word
if (letter != ' ' and word == 'Y'):

# incrementing the word


# count by 1

DEPT. OF CSE (AIML & DATA SCIENCE) 21


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

num_words += 1

# assigning value N to variable word because


until
# space will not encounter a word can not be
completed
word = 'N'

# condition to check that the encountered character is a


white space
elif (letter == ' '):

# incrementing the space


# count by 1
num_spaces += 1

# assigning value Y to variable word because


after
# white space a word is supposed to occur
word = 'Y'

# loop to iterate every character


for i in letter:

# condition to check white space


if(i !=" " and i !="\n"):

# incrementing character
# count by 1
num_charc += 1

# printing total word count


print("Number of words in text file: ",
num_words)

# printing total line count


print("Number of lines in text file: ",
num_lines)

# printing total character count


print('Number of characters in text file: ',
num_charc)

# printing total space count


print('Number of spaces in text file: ',
num_spaces)

# Driver Code:
if __name__ == '__main__':
fname = 'File1.txt'
try:
counter(fname)
except:
print('File not found')

DEPT. OF CSE (AIML & DATA SCIENCE) 22


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

Output:
Number of words in text file: 25
Number of lines in text file: 4
Number of characters in text file: 91

NAME OF THE PROGRAM: DEGREE:


COURSE NAME: SEMESTER:
COURSE CODE: COURSE CREDIT: 2
COURSE TYPE: LAB CONTACT HOURS: 4P

CO PO
Exp. List of Experiments Mapping Mapping Week
No.

1. Week
1

DEPT. OF CSE (AIML & DATA SCIENCE) 23


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

NAME OF THE PROGRAM: DEGREE:


COURSE NAME: SEMESTER:
COURSE CODE: COURSE CREDIT: 2
COURSE TYPE: LAB CONTACT HOURS: 4P

Rubrics for Lab

PO
Score Excellent Good Average (60%) Poor (40%) Abse CO PSO
Criteria (100%) (80%) nt Mapping Mapping
(0%)
Students can Students can Students can The student is not CO1, PO1,
identify the identify the identify the able to CO2 PO2,
problem/ problem/ problem/ analyze understand/analyze PSO1,
analyze the analyze the the problem/ Design /design the problem PSO2
problem/ Design problem/ the solutions and or interpret the
the solutions and Design the solve the problem problem in the
solve the solutions and by applying various specified language
problem by solve the algorithms with

DEPT. OF CSE (AIML & DATA SCIENCE) 24


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

applying various problem by appropriate test


algorithms with applying cases
appropriate test various
cases; students algorithms
1. Lab can include with
Participation boundary appropriate
conditions in test cases;
test cases; students can
students can include
modify the boundary
program or conditions in
design as per the test cases.
requirement of
the outcomes
from boundary
conditions (if
any).
Students can Students can Students can use Students are not CO3 PO5
exploit the full exploit the specified able to use the tool/
potential of the important tools/property/topics property/ topic
2. Effective tool/ property/ features of the as per the problem under consideration
utilization of topic under tool/ property/ requirement only for the specified
the modern consideration topic under under consideration language
tools and for the specified consideration for the specified
their language for the language
properties, specified
compilers language

Students can Students can Students can work Students are not CO4 PO9
work work ethically as individuals or able to work
effectively, as individuals members of a team effectively,
3. Individual or sincerely, and or as members sincerely, and
teamwork ethically as of a team ethically as
individuals or individuals or
members of a members of a team
team

Students will Students will Students will Students will not CO5 PO10
prepare effective prepare prepare effective prepare effective
documentation effective documentation of documentation of
of lab classes documentation lab classes lab classes
mentioning of lab classes mentioning problem mentioning
problem mentioning statements, input- objective, input-
4. Documentati statements, problem output output, test cases,
input-output, statements, boundary
on
appropriate test input-output, conditions
cases with test cases
boundary
conditions

DEPT. OF CSE (AIML & DATA SCIENCE) 25


Techno Main Salt Lake
EM-4/1, Sector-V, Salt Lake City, Kolkata - 700091

DEPT. OF CSE (AIML & DATA SCIENCE) 26

You might also like