例题1.猫和狗
创建两个文件 cats.txt 和 dogs.txt,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,并将其内容打印到屏幕上。将这些代码放在一个 try-except 代码块中,以便在文件不存在时捕获 FileNotFound 错误,并打印一条友好的消息。将其中一个文件移到另一个地方,并确认 except 代码块中的代码将正确地执行。
# 利用代码建立要求的cats.txt ,dogs.txt
with open('cats', 'w', encoding='utf-8')as file_object:
file_object.write('猫咪1号大花\n')
file_object.write('薛定谔的猫\n')
file_object.write('努力生活的猫\n')
file_object.write('不吃鱼的猫')
with open('dogs', 'w', encoding='utf-8')as file_object:
file_object.write('努力学习鸭\n')
file_object.write('努力开心鸭\n')
file_object.write('努力生活鸭\n')
file_object.write('不吃肉鸭')
# 打开文件cats.txt读取内容
try:
with open('cats', encoding='utf-8')as file_object:
contents = file_object.read()
except FileNotFoundError:
print('文件不存在~')
else:
print(contents)
# 打开文件dogs.txt读取文件内容
try:
with open('dogs', encoding='utf-8')as file_object:
contents = file_object.read()
except FileNotFoundError:
print('文件不存在~')
else:
print(contents)
我这里利用w模式自动建立不存在的文件,完成了题目中对于文件的要求,所以不会出现异常提醒。但是如果我们手动建立,故意有一个文件不建立,就会出现异常提醒。在我上篇笔记《python学习笔记23(异常处理)》里面有关于异常处理和读取模式结合例子的详细解说,有兴趣的话自行参考,这里只提供本例题的效果图:
例题2.沉默的猫和狗
修改你在例题1中编写的 except 代码块,让程序在文件不存在时一言不发。
这个知识点在《python学习笔记23(异常处理)》也提到了,这里就不在提供代码了。
例题3.0 常见单词
访问项目 Gutenberg(http://gutenberg.org/),并找一些你想分析的图书。下载这些作品的文本文件或将浏览器中的原始文本复制到文本文件中。
你可以使用方法 count()来确定特定的单词或短语在字符串中出现了多少次。例如,下面的代码计算’row’在一个字符串中出现了多少次:
>>> line = "Row, row, row your boat"
>>> line.count('row')
2
>>> line.lower().count('row')
3
请注意,通过使用 lower()将字符串转换为小写,可捕捉要查找的单词出现的所有次数,而不管其大小写格式如何。编写一个程序,它读取你在项目 Gutenberg 中获取的文件,并计算单词’the’在每个文件中分别出现了多少次。
# 打开文件cats.txt读取内容
try:
with open('cats', encoding='utf-8')as file_object:
contents1 = file_object.read()
number1 = contents1.count('the')
contents2 = contents1.lower()
number2 = contents2.count('the')
except FileNotFoundError:
print('文件cats.txt不存在~')
else:
# 原文本内容里面’the‘的个数
print(contents1)
print(number1)
# 利用lower()函数处理之后文本内容里面’the‘的个数
print(contents2)
print(number2)
The boy is so clever
The water is so warm
I so like the feeling.
the cat,the dog
3
the boy is so clever
the water is so warm
i so like the feeling.
the cat,the dog
5
我发现利用count函数计算’the’的个数,像‘weather’这种包含’the’的也会统计上,请问有大佬知道这种怎么解决呢?