Program
9. Count Uppercase and Lowercase Letters in a Text File
def count_case_letters(filename="[Link]"):
"""Counts and displays the number of uppercase and lowercase
letters in a text file."""
uppercase_count = 0
lowercase_count = 0
try:
with open(filename, 'r') as file:
content = [Link]()
for char in content:
if [Link]():
uppercase_count += 1
elif [Link]():
lowercase_count += 1
print(f"--- Analysis of '{filename}' ---")
print(f"Total Uppercase Letters: {uppercase_count}")
print(f"Total Lowercase Letters: {lowercase_count}")
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
# You may need to create a dummy file for testing:
# with open(filename, 'w') as f:
# [Link]("Hello World. This is a Test File.")
# Example usage (assuming '[Link]' exists):
# count_case_letters("[Link]")
10. Count Occurrences of a Specific Word in a Text File
import re
def count_word_frequency(filename="[Link]",
target_word="the"):
"""Counts the number of times a specific word appears in a text
file."""
count = 0
target_word = target_word.lower()
try:
with open(filename, 'r') as file:
content = [Link]()
# Use regex to find all words, then filter for the target
word
# \b matches word boundaries
words = [Link](r'\b\w+\b', [Link]())
for word in words:
if word == target_word:
count += 1
print(f"--- Analysis of '{filename}' ---")
print(f"The word '{target_word}' appears {count} times.")
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
# Example usage (assuming '[Link]' exists):
# count_word_frequency("[Link]", "The")
11. Display Lines Starting with a Vowel
def display_vowel_lines(filename="[Link]"):
[span_1](start_span)"""Displays all lines from a text file that
start with a vowel ('A', 'E', 'I', 'O', 'U', or their lowercase
equivalents)[span_1](end_span)."""
vowels = 'AEIOUaeiou'
found_lines = 0
print(f"\n--- Lines in '{filename}' starting with a Vowel ---")
try:
with open(filename, 'r') as file:
for line in file:
# Use strip() to remove leading/trailing whitespace,
including newline
stripped_line = [Link]()
if stripped_line and stripped_line[0] in vowels:
print(stripped_line.rstrip('\n')) # Print without extra
newline
found_lines += 1
if found_lines == 0:
print("No lines found starting with a vowel.")
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
# Example usage (assuming '[Link]' exists):
# display_vowel_lines("[Link]")
12. Read Student Records from a Binary File (Marks > 75)
This requires the pickle module for handling Python objects (like
dictionaries or lists of student data) in a binary file.
import pickle
import os # Used for file existence check
STUDENT_FILE = "[Link]"
# Helper function to create a dummy file for testing purposes
def create_dummy_student_file():
"""Creates a sample binary file with student records."""
students = [
{'RollNo': 101, 'Name': 'Alice', 'Marks': 85},
{'RollNo': 102, 'Name': 'Bob', 'Marks': 70},
{'RollNo': 103, 'Name': 'Charlie', 'Marks': 92},
{'RollNo': 104, 'Name': 'David', 'Marks': 75},
{'RollNo': 105, 'Name': 'Eve', 'Marks': 68},
]
try:
with open(STUDENT_FILE, 'wb') as file:
[Link](students, file)
print(f"Dummy file '{STUDENT_FILE}' created successfully.")
except Exception as e:
print(f"Error creating file: {e}")
def display_high_marks_students(filename=STUDENT_FILE,
required_marks=75):
"""Reads student records from a binary file and displays those
with Marks above 75."""
if not [Link](filename):
print(f"Error: Binary file '{filename}' not found. Please create
it first.")
# create_dummy_student_file() # Uncomment to auto-create
for testing
return
high_scorers = 0
print(f"\n--- Students with Marks > {required_marks} ---")
try:
with open(filename, 'rb') as file:
# Assuming the file stores a list of dictionaries (records)
students = [Link](file)
for student in students:
if 'Marks' in student and student['Marks'] >
required_marks:
print(f"RollNo: {student['RollNo']}, Name:
{student['Name']}, Marks: {student['Marks']}")
high_scorers += 1
if high_scorers == 0:
print("No students found with marks above 75.")
except EOFError:
# Raised if the file is empty or corrupted
print("Error: End of file reached unexpectedly (file might be
empty or corrupted).")
except Exception as e:
print(f"An error occurred during file reading: {e}")
# Example usage:
# create_dummy_student_file() # Run once to create the file
# display_high_marks_students()
14 & 15. Menu-Driven MySQL Operations
This combines the remaining operations (INSERT, UPDATE,
DELETE, and SELECT queries) into a single menu-driven program.
import [Link]
# DB_CONFIG is the same as defined in problem 13
# --- Helper function for establishing connection ---
def get_db_connection():
try:
return [Link](**DB_CONFIG)
except [Link] as err:
print(f"Error connecting to MySQL: {err}")
return None
# --- Operation Functions ---
def insert_record(conn):
[span_3](start_span)"""INSERT a new record into the BOOKS
table[span_3](end_span)."""
try:
book_id = int(input("Enter BookID: "))
title = input("Enter Title: ")
author = input("Enter Author: ")
price = float(input("Enter Price: "))
cursor = [Link]()
insert_query = "INSERT INTO BOOKS (BookID, Title, Author,
Price) VALUES (%s, %s, %s, %s)"
record = (book_id, title, author, price)
[Link](insert_query, record)
[Link]()
print("Record inserted successfully.")
[Link]()
except ValueError:
print("Invalid input for ID or Price.")
except [Link] as err:
print(f"Error inserting record: {err}")
def update_price(conn):
[span_4](start_span)"""UPDATE the price of a specific book
(based on BookID)[span_4](end_span)."""
try:
book_id = int(input("Enter BookID to update price: "))
new_price = float(input("Enter new Price: "))
cursor = [Link]()
update_query = "UPDATE BOOKS SET Price = %s WHERE
BookID = %s"
[Link](update_query, (new_price, book_id))
[Link]()
if [Link] > 0:
print("Price updated successfully.")
else:
print("BookID not found.")
[Link]()
except ValueError:
print("Invalid input for ID or Price.")
except [Link] as err:
print(f"Error updating record: {err}")
def delete_record(conn):
[span_5](start_span)"""DELETE a record (based on BookID)
[span_5](end_span)."""
try:
book_id = int(input("Enter BookID to delete: "))
cursor = [Link]()
delete_query = "DELETE FROM BOOKS WHERE BookID = %s"
[Link](delete_query, (book_id,))
[Link]()
if [Link] > 0:
print("Record deleted successfully.")
else:
print("BookID not found.")
[Link]()
except ValueError:
print("Invalid input for ID.")
except [Link] as err:
print(f"Error deleting record: {err}")
def select_by_author(conn):
[span_6](start_span)"""SELECT and display all books written by
a specific Author[span_6](end_span)."""
try:
author_name = input("Enter Author name to search: ")
cursor = [Link]()
select_query = "SELECT * FROM BOOKS WHERE Author =
%s"
[Link](select_query, (author_name,))
print(f"\n--- Books by {author_name} ---")
display_results([Link]())
[Link]()
except [Link] as err:
print(f"Error selecting records: {err}")
def select_max_price(conn):
[span_7](start_span)"""SELECT and display the book with the
maximum price[span_7](end_span)."""
try:
cursor = [Link]()
# Subquery to find the max price and then select the
corresponding book
select_query = "SELECT * FROM BOOKS WHERE Price =
(SELECT MAX(Price) FROM BOOKS)"
[Link](select_query)
print("\n--- Book(s) with Maximum Price ---")
display_results([Link]())
[Link]()
except [Link] as err:
print(f"Error selecting records: {err}")
def select_author_starts_with_A(conn):
[span_8](start_span)"""Display all records from the table where
the Author name starts with the letter 'A'[span_8](end_span)."""
try:
cursor = [Link]()
select_query = "SELECT * FROM BOOKS WHERE Author LIKE
'A%'"
[Link](select_query)
print("\n--- Books by Author starting with 'A' ---")
display_results([Link]())
[Link]()
except [Link] as err:
print(f"Error selecting records: {err}")
def display_results(results):
"""Helper function to format and print query results."""
if not results:
print("No records found.")
return
print(f"| {'BookID':<6} | {'Title':<30} | {'Author':<20} |
{'Price':<8} |")
print("-" * 70)
for row in results:
print(f"| {row[0]:<6} | {row[1]:<30} | {row[2]:<20} |
{row[3]:<8.2f} |")
# --- Main Menu Function ---
def mysql_menu():
conn = get_db_connection()
if not conn:
return
while True:
print("\n--- MySQL BOOKS Table Operations ---")
[span_9](start_span)print("1. INSERT a new record[span_9]
(end_span)")
[span_10](start_span)print("2. UPDATE Price (by BookID)
[span_10](end_span)")
[span_11](start_span)print("3. DELETE a record (by BookID)
[span_11](end_span)")
[span_12](start_span)print("4. SELECT by specific
Author[span_12](end_span)")
[span_13](start_span)print("5. SELECT Book(s) with
Maximum Price[span_13](end_span)")
[span_14](start_span)print("6. SELECT by Author starting
with 'A'[span_14](end_span)")
print("7. Exit")
choice = input("Enter your choice (1-7): ")
if choice == '1': insert_record(conn)
elif choice == '2': update_price(conn)
elif choice == '3': delete_record(conn)
elif choice == '4': select_by_author(conn)
elif choice == '5': select_max_price(conn)
elif choice == '6': select_author_starts_with_A(conn)
elif choice == '7':
print("Exiting MySQL Program.")
if conn.is_connected():
[Link]()
print("Database connection closed.")
break
else:
print("Invalid choice. Please enter a number between 1
and 7.")
# To run the MySQL menu (ensure DB_CONFIG is set):
# mysql_menu()