Python编程:从入门到实践 第 10 章 文件和异常 课后练习 10-1~10-5

10-1 Python 学习笔记 :在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的 Python 知识,其中每一行都以 “In Python you can” 打头。将这个文件命名为learning_python.txt ,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在 with 代码块外打印它们。

# 1
filename = 'learning_python.txt'
with open(filename) as file_object:
    content = file_object.read()
    print(content)
# 2
filename = 'learning_python.txt'
with open(filename) as file_object:
    for line in file_object.readlines():
        print(line.rstrip())
#3
filename = 'learning_python.txt'
with open(filename) as file_object:
    lines = file_object.readlines()

h_string = ''
for line in lines:
    h_string += line.rstrip()
print(h_string)


10-2 C 语言学习笔记 :可使用方法 replace() 将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如何将句子中的 'dog' 替换为 'cat':
>>> message = "I really like dogs."
>>> message.replace('dog', 'cat')
'I really like cats.'
读取你刚创建的文件 learning_python.txt 中的每一行,将其中的 Python 都替换为另一门语言的名称,如 C 。将修改后的各行都打印到屏幕上。

filename = 'learning_python.txt'
with open(filename) as file_object:
    for line in file_object:
        line1 = line.replace('Python', 'C')
        print(line1.rstrip())

10-3 访客 :编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件 guest.txt 中。

filename = 'guest.txt'
with open(filename, 'w') as file_object:
    name = input("Please enter your name:")
    file_object.write('Hello, ' + name.title() + '!\n')


10-4 访客名单 :编写一个 while 循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件 guest_book.txt 中。确保这个文件中的每条记录都独占一行。

filename = 'guest_book.txt'
with open(filename, 'w') as file_object:

    while True:
        name = input("Please enter your name:")
        if name != 'q':
            file_object.write('Hello, ' + name.title() + '!\n')
        else:
            break


with open(filename) as file_object:
    content = file_object.read()
    print(content)
Please enter your name:gg
Please enter your name:ee
Please enter your name:ff
Please enter your name:q
Hello, Gg!
Hello, Ee!
Hello, Ff!


10-5 关于编程的调查 :编写一个 while 循环,询问用户为何喜欢编程。每当用户输入一个原因后,都将其添加到一个存储所有原因的文件中。

filename = 'programing_like.txt'
with open(filename, 'w') as file_object:
    while True:
        message = input("Why you like make programing? Enter 'q', if you want quit:\n")
        if message != 'q':
            file_object.write(message.rstrip() + '\n')
        else:
            break
with open(filename) as file_object:
    content = file_object.read()
    print(content)

10-6 加法运算 :提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发 TypeError 异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获 TypeError 异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。

print("Give me two numbers, and I'll add them.")

try:
    first_number = int(input("\nFirst number: "))
    second_number = int(input("Second number: "))

except ValueError:
    print("Please enter numeric digits only.")
else:
    answer = first_number + second_number
    print(answer)
Give me two numbers, and I'll add them.

First number: 12
Second number: dd
Please enter numeric digits only.


10-7 加法计算器 :将你为完成练习 10-6 而编写的代码放在一个 while 循环中,让用户犯错(输入的是文本而不是数字)后能够继续输入数字。

print("Give me two numbers, and I'll add them.")

while True:
    try:
        first_number = int(input("\nFirst number: "))
        second_number = int(input("Second number: "))

    except ValueError:
        print("Please enter numeric digits only.")
        pass
    else:
        answer = first_number + second_number
        print(answer)
Give me two numbers, and I'll add them.

First number: dd
Please enter numeric digits only.

First number: 12
Second number: 14
26

First number: 12
Second number: dd
Please enter numeric digits only.

First number: 


10-8 猫和狗 :创建两个文件 cats.txt 和 dogs.txt ,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,并将其内容打印到屏幕上。将这些代码放在一个 try-except 代码块中,以便在文件不存在时捕获 FileNotFound 错误,并打印一条友好的消息。将其中一个文件移到另一个地方,并确认 except 代码块中的代码将正确地执行。

def print_message(file_name):
    try:
        with open(file_name) as file_object:
            content = file_object.read()
    except FileNotFoundError:
        msg = "Sorry, the file " + file_name + " does not exist."
        print(msg)
    else:
        print(content)


file_names = ['cat.txt', 'dog.txt']
for file_name in file_names:
    print_message(file_name)


10-9 沉默的猫和狗 :修改你在练习 10-8 中编写的 except 代码块,让程序在文件不存在时一言不发。

def print_message(file_name):
    try:
        with open(file_name) as file_object:
            content = file_object.read()
    except FileNotFoundError:
        pass
    else:
        print(content)


file_names = ['cat.txt', 'dog.txt']
for file_name in file_names:
    print_message(file_name)

10-10 常见单词 :访问项目 Gutenberg ( http://gutenberg.org/ ),并找一些你想分析的图书。下载这些作品的文本文件或将浏览器中的原始文本复制到文本文件中。
你可以使用方法 count() 来确定特定的单词或短语在字符串中出现了多少次。例如,下面的代码计算 'row' 在一个字符串中出现了多少次:
>>> line = "Row, row, row your boat"
>>> line.count('row')
2
>>> line.lower().count('row')
3
请注意,通过使用 lower() 将字符串转换为小写,可捕捉要查找的单词出现的所有次数,而不管其大小写格式如何。
编写一个程序,它读取你在项目 Gutenberg 中获取的文件,并计算单词 'the' 在每个文件中分别出现了多少次。

def count_words(filename):
    """ 计算一个文件大致包含多少个单词 """
    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        msg = "Sorry, the file " + filename + " does not exist."
        print(msg)
    else:
        # 计算文件大致包含多少个单词
        count_num = contents.lower().count('the')
        print("The file " + filename + " has about " + str(count_num) + " 'the'.")


filenames = ['alice.txt', 'little_women.txt' 'siddhartha.txt', 'moby_dick.txt']
for filename in filenames:
    count_words(filename)
The file alice.txt has about 2505 'the'.
Sorry, the file little_women.txtsiddhartha.txt does not exist.
The file moby_dick.txt has about 20028 'the'.

猜你喜欢

转载自blog.csdn.net/hjk120key3/article/details/82892382
今日推荐