我们可以编写函数来通过对文件字符串的split和长度计算(len)来获取个txt文件的字数。
def count_words(filename):
try:
with open(filename,'r',encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
return(f"The file {filename} doesn't exit. Please check!")
except UnicodeDecodeError:
return(f"Please endoce the file with utf-8 format.")
words = contents.split()
return len(words)
注意到,我们在其中使用了try-except语句来处理了找不到文件时的异常(FileNotFound)。
这样,我们可以定义小说txt文件列表,然后通过for循环来对这些文件进行操作,依次统计出各个小说的字数了,如果文件不存在,就会优雅地报错并且不影响后续程序的执行。
book_list = ['alice.txt','princess.txt','siddhartha.txt','moby.txt']
for book in book_list:
print(count_words(book))
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200517101425221.png)
|