Lab Report 05

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

Lab Report 05

Problem Statement 01:


Write a program to read through a file and print the contents of the file
(line by line) all in upper case. Executing the program will look as follows:
(mbox-data)

#code:
def uppercase(file_name):
try:
with open(file_name) as file:
for line in file:
print(line.upper(), end='')
except:
print(f"File '{file_name}' not found.")
file_name = input("Enter a file name: ")
uppercase(file_name)

#output:
Enter a file name: ashraful.txt
File 'ashraful.txt' not found.

Problem Statement 02:


Write a program to prompt for a file name, and then read through the file
and look for lines of the form:
X-DSPAM-Confidence: 0.8475

#code:
name = input("file name: ")
try:
file = open(name, 'r')
except:
print("not found.")
exit()
count = 0
t_c = 0.0
for line in file:
if line.startswith("X-DSPAM-Confidence:"):
count += 1

Lab Report 05 1
colon_index = line.find(":")
confidence = float(line[colon_index + 1:].strip())
t_c += confidence
file.close()
if count > 0:
a_c = t_c / count
print("average spam confidence:", a_c)
else:
print("no lines with spam confidence found.")

#output:
file name: mbox-short.txt
average spam confidence: 0.7507185185185187

Problem Statement 03:


Find all unique words in a file. Shakespeare used over 20,000 words in
his works. But how would you determine that? How would you pro-
duce a list of all the words that Shakespeare used? Would you down-
load all his work, read it, and track all unique words by hand? Let’s
use Python to achieve that instead. List all unique words, sorted in al-
phabetical order, that are stored in a file romeo.txt containing a sub-
set of Shakespeare’s work. To get started, download a copy of the file
(https://www.py4e.com/code3/romeo.txt). Create a list of unique words,
which will contain the final result. Write a program to open the file
romeo.txt and read it line by line. For each line, split the line into a list of
words using the split function. For each word, check to see if the word is
already in the list of unique words. If the word is not in the list of unique
words, add it to the list. When the program completes, sort and print the
list of unique words in alphabetical order.

#code:
def extract_unique_words(file_name):
unique_words = []
try:
with open(file_name, 'r') as file:
for line in file:
words = line.split()
for word in words:
if word not in unique_words:

Lab Report 05 2
unique_words.append(word)
except:
print(f"File '{file_name}' not found.")
return []
return sorted(unique_words)
# Provide the file name or its full path
file_name = 'romeo.txt'
# Call the function to extract unique words and print them
unique_words = extract_unique_words(file_name)
for word in unique_words:
print(word)

#output:
'Arise', 'But', 'It', 'Juliet', 'Who', 'already',
'and', 'breaks', 'east', 'envious', 'fair', 'grief',
'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft',
'sun', 'the', 'through', 'what', 'window',
'with', 'yonder'

Problem Statement 04:


Remove the following stopwords from the romeo.txt file and then find the
list of unique words.
stp = [”But”,’is’,’the’,’with’,’and’]

import string
def extract_unique_words(file_name):
unique_words = []
stop_words = ["but", "is", "the", "with", "and"]
punctuation = set(string.punctuation)
try:
with open(file_name, 'r') as file:
for line in file:
line = line.strip().lower()
words = ''
for ch in line:
if ch not in punctuation:
words += ch
words = words.split()
words = [word for word in words if word.lower() not in stop_words and word not in unique_w
ords]
unique_words.extend(words)
except FileNotFoundError:
print(f"File '{file_name}' not found.")
return []
return sorted(unique_words)
# Provide the file name or its full path

Lab Report 05 3
file_name = 'romeo.txt'
# Call the function to extract unique words after removing stopwords
unique_words = extract_unique_words(file_name)
# Print the unique words
for word in unique_words:
print(word)

#output:
'Arise', 'It', 'Juliet', 'Who', 'already','breaks', 'east', 'envious', 'fair', 'grief', 'k
ill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'through', 'what', 'window', 'yond
er'

Problem Statement 05:

#code:
# Prompt for the file name
file_name = input("Enter a file name: ")
# Initialize variables
sender_emails = []
from_line_count = 0
try:
with open(file_name, 'r') as file:
for line in file:
if line.startswith('From '):
# Split the line into words
words = line.split()
# Extract the sender's email address
sender_email = words[1]
# Print the sender's email address
print(sender_email)
# Add the email address to the list
sender_emails.append(sender_email)
# Increment the from_line_count
from_line_count += 1
except FileNotFoundError:
print(f"File '{file_name}' not found.")
# Print the total count of From lines
print(f"There were {from_line_count} lines in the file with From as the first word")

Enter a file name: mbox-short.txt


[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

Lab Report 05 4
[email protected]
.....

Problem Statement 06:


Rewrite the program that prompts the user for a list of numbers and prints
out the maximum and minimum of the numbers at the end when the user
enters “done”. Write the program to store the numbers the user enters in a
list and use the max() and min() functions to compute the maximum and
minimum numbers after the loop completes.

#code
numbers = [] # List to store the numbers
while True:
user_input = input("Enter a number (or 'done' to finish): ")
if user_input == 'done':
break
try:
number = float(user_input)
numbers.append(number)
except ValueError:
print("Invalid input. Please enter a number or 'done'.")
if numbers:
maximum = max(numbers)
minimum = min(numbers)
print("Maximum number:", maximum)
print("Minimum number:", minimum)
else:
print("No numbers entered.")

#output:
Enter a number (or 'done' to finish): 59
Enter a number (or 'done' to finish): 10
Enter a number (or 'done' to finish): 48
Enter a number (or 'done' to finish): done
Maximum number: 59.0
Minimum number: 10.0

Lab Report 05 5

You might also like