小白自学,仅作为个人记录。
Exercise 1: Write a program to read through a fifile and print the contents of the fifile (line
by line) all in upper case. Executing the program will look as follows:
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
for line in fhand:
line = line.upper()
print(line)
Exercise 2: Write a program to prompt for a file name, and then readthrough the file and look for lines of the form:
X-DSPAM-Confidence: 0.8475
When you encounter a line that starts with “X-DSPAM-Confifidence:” pull apart the line
to extract the flfloating-point number on the line. Count these lines and then compute the
total of the spam confifidence values from these lines. When you reach the end of the fifile,
print out the average spam confifidence.
Enter the file name: mbox.txt
Average spam confidence: 0.894128046745
Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519
from numpy import average
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
spam_confidence_list = []
for line in fhand:
line = line.strip()
if line.startswith('X-DSPAM-Confidence:'):
spam_confidence = eval(line[19:])
spam_confidence_list.append(spam_confidence)
print(line)
total_spam_confidence = sum(spam_confidence_list)
average_spam_confidence = average(spam_confidence_list)
print(total_spam_confidence)
print(average_spam_confidence)
xercise 3: Sometimes when programmers get bored or want to have abit of fun, they add a harmless Easter Egg to their program. Modify theprogram that prompts the user for the file name so that it prints afunny message when the user types in the exact file name "na na booboo". The program should behave normally for all other files whichexist and don't exist. Here is a sample execution of the program:
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
wrong_file = str(fname)
print(f"{wrong_file.upper()} - YOU'VE BEEN PUNK'D")
exit()
count = 0
for line in fhand:
if line.startswith('Subject:'):
count += 1
print('Ther were', count, 'subject lines in', fname)