猫的数量
您正在做一个自然语言处理项目,想要找出优秀作家为何如此出色。您当前的假设是:优秀作家会经常谈到猫。为验证这一点,您想统计 Lewis Carroll 所著 "Alice's Adventures in Wonderland" 中单词 "cat" 出现的次数。您已经下载了包含整本书内容的文本文件 alice.txt。
本练习是课程的一部分
Python 函数编写
练习说明
- 使用
open()上下文管理器打开alice.txt,并将文件对象赋给变量file。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Open "alice.txt" and assign the file to "file"
____ ____('alice.txt') ____ file:
text = file.read()
n = 0
for word in text.split():
if word.lower() in ['cat', 'cats']:
n += 1
print('Lewis Carroll uses the word "cat" {} times'.format(n))