# Menu function
def menu():
while True:
print("\n1. Write Story")
print("2. Display Story")
print("3. File Statistics")
print("4. Copy Words Starting with Vowels")
print("5. EXIT")
choice = int(input("Enter your choice: "))
if choice == 1:
write_story()
elif choice == 2:
display_story()
elif choice == 3:
statistics()
elif choice == 4:
copy_vowels()
elif choice == 5:
print("Exiting program.")
break
else:
print("Invalid choice")
# i) Write n lines into Story.txt
def write_story():
with open("Story.txt", "w") as f:
n = int(input("Enter number of lines: "))
for i in range(n):
f.write(input() + "\n")
print("Story written successfully")
# ii) Display contents of the file
def display_story():
try:
with open("Story.txt", "r") as f:
print("\nStory Contents:\n")
print(f.read())
except FileNotFoundError:
print("Error: File does not exist")
# iii) Display file statistics
def statistics():
try:
with open("Story.txt", "r") as f:
text = f.read()
characters = len(text)
words = text.split()
lines = text.split("\n")
print("Character Count:", characters)
print("Word Count:", len(words))
print("Line Count:", len(lines) - 1)
capital_count = 0
for word in words:
if word[0].isupper():
capital_count += 1
print("Words starting with capital letter:", capital_count)
except FileNotFoundError:
print("Error: File does not exist")
# iv) Copy words starting with vowels to vowels.txt
def copy_vowels():
try:
with open("Story.txt", "r") as f:
text = f.read()
words= text.split()
with open("vowels.txt", "w") as fw:
for word in words:
if word[0].lower() in "aeiou":
fw.write(word + "\n")
print("\nContents of vowels.txt:")
with open("vowels.txt", "r") as fr:
print(fr.read())
except FileNotFoundError:
print("Error: File does not exist")
# Call menu
menu()
No comments:
Post a Comment