Python for Everybody(PY4E) Chapter7

该程序演示了如何使用Python读取文件内容,将每一行转换为大写并打印。此外,它查找以"X-DSPAM-Confidence:"开头的行,提取浮点数,计算这些值的总和和平均值。程序还包括一个特殊功能,当用户输入"nanabooboo"时,会显示一个有趣的彩蛋消息。
摘要由CSDN通过智能技术生成
小白自学,仅作为个人记录。
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)

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值