You are on page 1of 13

CS Project

1)Write a Python program to count the number of characters (character frequency) in a string.

Sample String : google.com'

Expected Result : {'o': 3, 'g': 2, '.': 1, 'e': 1, 'l': 1, 'm': 1, 'c': 1}

You can use the following Python program to count the number of characters (character frequency) in
a string:

def count_characters(string):

char_frequency = {}

for char in string:

if char in char_frequency:

char_frequency[char] += 1

else:

char_frequency[char] = 1

return char_frequency

# Test the function

sample_string = 'google.com'

result = count_characters(sample_string)

print(result)

output: {'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1}

In this program, we define the count_characters function that takes a string as input. It initializes an
empty dictionary char_frequency to store the character frequencies.

Next, we iterate over each character in the string. If the character already exists as a key in the
char_frequency dictionary, we increment its value by 1. Otherwise, we add the character as a new
key in the dictionary with a value of 1.

Finally, we return the char_frequency dictionary, which contains the character frequencies. In the
example above, the program counts the characters in the sample string 'google.com' and produces
the expected result.

2)Write an interactive menu driven program with the following four functions:

a) To create a text file called “Nation.txt”

b) Display the file

c) Append relevant content to the file

d) Make a copy of the file

e) Count the total number of “the” in the file

Here's a Python program that implements an interactive menu-driven program with the requested
functions:

import shutil

def create_file():

file_name = "Nation.txt"

with open(file_name, "w") as file:

print(f"File '{file_name}' created successfully.")

def display_file():

file_name = "Nation.txt"

try:

with open(file_name, "r") as file:

content = file.read()

print(f"Content of '{file_name}':\n{content}")

except FileNotFoundError:

print(f"File '{file_name}' does not exist.")

def append_content():

file_name = "Nation.txt"

content = input("Enter the content to append: ")

with open(file_name, "a") as file:


file.write(content + "\n")

print("Content appended successfully.")

def make_copy():

original_file = "Nation.txt"

copy_file = "Nation_copy.txt"

try:

shutil.copyfile(original_file, copy_file)

print(f"File '{original_file}' copied to '{copy_file}' successfully.")

except FileNotFoundError:

print(f"File '{original_file}' does not exist.")

def count_occurrences():

file_name = "Nation.txt"

try:

with open(file_name, "r") as file:

content = file.read()

count = content.count("the")

print(f"Total occurrences of 'the' in '{file_name}': {count}")

except FileNotFoundError:

print(f"File '{file_name}' does not exist.")

def print_menu():

print("\nMenu:")

print("a) Create file 'Nation.txt'")

print("b) Display file 'Nation.txt'")

print("c) Append content to file 'Nation.txt'")

print("d) Make a copy of file 'Nation.txt'")


print("e) Count the total number of 'the' in file 'Nation.txt'")

print("q) Quit")

# Main program loop

while True:

print_menu()

choice = input("Enter your choice: ")

if choice == "a":

create_file()

elif choice == "b":

display_file()

elif choice == "c":

append_content()

elif choice == "d":

make_copy()

elif choice == "e":

count_occurrences()

elif choice == "q":

print("Exiting the program.")

break

else:

print("Invalid choice. Please try again.")

This program provides an interactive menu to perform various operations on a file called "Nation.txt".

The menu options are as follows:

Option 'a' creates the file "Nation.txt".


Option 'b' displays the content of the file "Nation.txt".
Option 'c' appends relevant content to the file "Nation.txt".
Option 'd' makes a copy of the file "Nation.txt" with the name "Nation_copy.txt".
Option 'e' counts the total number of occurrences of the word "the" in the file "Nation.txt".
Option 'q' quits the program.

You can run this program, and it will prompt you to enter your choice from the menu. Depending on
the choice you make, it will execute the corresponding function.

3) Write a function in Python to search and display details of all those students, whose stream is

“HUMANITIES” from pickled file “Student.dat”. Assuming the pickled file containing

following data for the students:- Roll, Name, Stream, Percent.

To search and display details of students whose stream is "HUMANITIES" from a pickled file called
"Student.dat," you can use the following Python function

import pickle

def search_students_by_stream(stream):

try:

with open("Student.dat", "rb") as file:

students = pickle.load(file)

humanities_students = [student for student in students if student['Stream'] == stream]

if len(humanities_students) == 0:

print(f"No students found with stream '{stream}'.")

else:

print("Students with stream 'HUMANITIES':")

for student in humanities_students:

print(f"Roll: {student['Roll']}")

print(f"Name: {student['Name']}")

print(f"Stream: {student['Stream']}")

print(f"Percent: {student['Percent']}")

print()

except FileNotFoundError:

print("File 'Student.dat' not found.")


# Example usage

search_students_by_stream("HUMANITIES")

In this function, we open the "Student.dat" file in binary mode using the "rb" mode. We load the data
from the file using the pickle.load() function, which returns a list of dictionaries representing the
students.

We then use a list comprehension to filter out the students whose stream matches the provided
stream parameter.

If there are no students found with the specified stream, we print a corresponding message.
Otherwise, we iterate over the humanities_students list and display the details of each student,
including their roll number, name, stream, and percentage.

You can call this function with the desired stream (e.g., "HUMANITIES") to search and display the
details of the relevant students from the pickled file.

4)Write a function MULTIPLEX( ) in python to search and delete all the content in a

pickled file CINEMA.DAT, where MTYPE is matching with the value ‘Comedy’. File

contains following details about Movies – (MNO,MNAME, MTYPE).

To search and delete all the content in a pickled file called "CINEMA.DAT" where MTYPE matches
the value "Comedy", you can use the following Python function:

import pickle

import os

def multiplex():

try:

with open("CINEMA.DAT", "rb") as file:

movies = pickle.load(file)

# Filter movies with MTYPE matching 'Comedy'

comedy_movies = [movie for movie in movies if movie['MTYPE'] == 'Comedy']

if len(comedy_movies) == 0:

print("No movies found with MTYPE 'Comedy'.")


else:

# Delete the content in the file

os.remove("CINEMA.DAT")

print(f"{len(comedy_movies)} movies with MTYPE 'Comedy' deleted successfully.")

except FileNotFoundError:

print("File 'CINEMA.DAT' not found.")

# Example usage

multiplex()

In this function, we open the "CINEMA.DAT" file in binary mode using the "rb" mode. We load the
data from the file using the pickle.load() function, which returns a list of dictionaries representing the
movies.

We then use a list comprehension to filter out the movies whose MTYPE matches the value
'Comedy'.

If there are no movies found with the specified MTYPE, we print a corresponding message.
Otherwise, we delete the content of the file using the os.remove() function, effectively deleting the file.
You can replace this line with other operations, such as truncating the file or modifying the content as
per your requirements.

You can call this function to search and delete the content from the pickled file "CINEMA.DAT" where
MTYPE matches the value 'Comedy'.

5) A binary file “Store.dat” has structure [ItemNo, Item_Name, Company, Price].

a) Write a function CountRec(Company) in Python which accepts the Company name as

parameter and count and return number of Items by the given Company are stored in the

binary file “Store.dat”.

b) Write a function AddRecord(<List>) which accepts a List of the record [ItemNo,

Item_Name, Company, Price] and appends in the binary file “Store.Dat”

Here's the implementation of the two functions you requested:

import struct

def CountRec(company):

count = 0
try:

with open("Store.dat", "rb") as file:

while True:

record = file.read(16) # Read 16 bytes (4 bytes for each field)

if not record:

break

item_no, item_name, record_company, price = struct.unpack("ii8s f", record)

decoded_company = record_company.decode().strip('\x00') # Convert bytes to string and


remove null characters

if decoded_company == company:

count += 1

except FileNotFoundError:

print("File 'Store.dat' not found.")

return count

def AddRecord(record_list):

item_no, item_name, company, price = record_list

try:

with open("Store.dat", "ab") as file:

encoded_company = company.encode().ljust(8, b'\x00') # Convert string to bytes and pad


with null characters

record = struct.pack("ii8s f", item_no, item_name, encoded_company, price)

file.write(record)

print("Record added successfully.")

except FileNotFoundError:

print("File 'Store.dat' not found.")

# Example usage

company_count = CountRec("Company A")


print(f"Number of items by Company A: {company_count}")

record = [1, "Item A", "Company B", 9.99]

AddRecord(record)

In the CountRec function:

We open the "Store.dat" file in binary mode using the "rb" mode.
We read the file in a loop, reading 16 bytes at a time (4 bytes for each field).
Using the struct.unpack function, we unpack the bytes into the respective fields: item_no,
item_name, record_company, and price.
We decode the record_company bytes into a string and remove any null characters ('\x00').
If the decoded company matches the provided company parameter, we increment the count.
Finally, we return the count.

In the AddRecord function:

We receive a list containing the record fields as a parameter.


We open the "Store.dat" file in binary mode using the "ab" mode (appending binary data).
We encode the company string into bytes and pad it with null characters ('\x00') to a fixed length
of 8 bytes.
Using the struct.pack function, we pack the fields into a binary record.
We write the record to the file.
Finally, we print a success message.

You can call these functions as per your requirements, providing the company name for counting
records and the record list for adding a new record to the "Store.dat" binary file.

6)A blood bank maintains data file “Blood.dat” that contains following information for every

donor: donor name, donor date of birth, donor address, donor phone number and donor blood

group. Write a complete program to do the following:

a) Create a file of the donor

b) Append a record in the file

c) Display the records

d) Given the blood group display name, address of the donor

e) Modify the existing information of the donor

Here's a complete program that performs the required operations on the "Blood.dat" data

file:import pickle
def create_file():

donor_data = []

with open("Blood.dat", "wb") as file:

pickle.dump(donor_data, file)

print("Donor file created successfully.")

def append_record():

with open("Blood.dat", "rb") as file:

donor_data = pickle.load(file)

donor = {}

donor['name'] = input("Enter donor name: ")

donor['date_of_birth'] = input("Enter donor date of birth: ")

donor['address'] = input("Enter donor address: ")

donor['phone_number'] = input("Enter donor phone number: ")

donor['blood_group'] = input("Enter donor blood group: ")

donor_data.append(donor)

with open("Blood.dat", "wb") as file:

pickle.dump(donor_data, file)

print("Record appended successfully.")

def display_records():

try:

with open("Blood.dat", "rb") as file:

donor_data = pickle.load(file)
if len(donor_data) == 0:

print("No donor records found.")

else:

for donor in donor_data:

print("Donor Details:")

print(f"Name: {donor['name']}")

print(f"Date of Birth: {donor['date_of_birth']}")

print(f"Address: {donor['address']}")

print(f"Phone Number: {donor['phone_number']}")

print(f"Blood Group: {donor['blood_group']}")

print()

except FileNotFoundError:

print("File 'Blood.dat' not found.")

def search_donor_by_blood_group(blood_group):

try:

with open("Blood.dat", "rb") as file:

donor_data = pickle.load(file)

found = False

for donor in donor_data:

if donor['blood_group'].lower() == blood_group.lower():

print("Donor Details:")

print(f"Name: {donor['name']}")

print(f"Address: {donor['address']}")

print()

found = True
if not found:

print(f"No donor found with blood group '{blood_group}'.")

except FileNotFoundError:

print("File 'Blood.dat' not found.")

def modify_donor_info():

try:

with open("Blood.dat", "rb") as file:

donor_data = pickle.load(file)

donor_name = input("Enter donor name to modify the information: ")

found = False

for donor in donor_data:

if donor['name'].lower() == donor_name.lower():

print("Current Donor Details:")

print(f"Name: {donor['name']}")

print(f"Date of Birth: {donor['date_of_birth']}")

print(f"Address: {donor['address']}")

print(f"Phone Number: {donor['phone_number']}")

print(f"Blood Group: {donor['blood_group']}")

print()

donor['date_of_birth'] = input("Enter modified date of birth: ")

donor['address'] = input("Enter modified address: ")

donor['phone_number'] = input("Enter modified phone number: ")

donor['blood_group'] = input("Enter modified blood group: ")


found = True

break

if not found:

print(f"No donor found with name '{donor_name}'.")

with open("Blood.dat", "wb") as file:

pickle.dump(donor_data, file)

You might also like