10-10常见单词
filename='smoke.txt'
with open(filename,encoding='utf-8') as f:
c=f.read().lower()
d=c.count('the')
print(f"The word 'the' has appear "+str(d)+" times in "+filename+".")
10-10处理多个文件,def函数,try-except代码块,pass关键字,split()方法,count()方法,read()方法
def count_words(filename):
try:
with open(filename,encoding='utf-8') as f:
contents=f.read().lower()#全文小写后读取为字符串赋值为变量contents
words_number=len(contents.split())#计算全篇总字数
number=contents.count('the')#计算'the'的数量
except FileNotFoundError:
print(f"\nSorry,the file {filename} was not found!!!")
#pass
else:
print(f"\nIn {filename},it has {words_number} words.")
print(f"This file contains "+str(number)+" 'the'.")
filenames=['alice.txt','smoke.txt','twilight.txt','dogs.txt','none.txt']
for filename in filenames:
count_words(filename)