方法spilt()以空格为分隔符将字符串拆分成多个部分,并将这些部分都存储在一个列表中;
def count_words(filename):
try:
# 有可能产生错误的代码
with open(filename, "r", encoding = "utf-8") as f:
contents = f.read()
except FileNotFoundError:
# 发生找不到文件错误时运行
print(f"Sorry, the file {filename} does not exist.")
# 中间还可以加上其他可能的错误类型:except 错误类型
except:
# 产生其他错误会运行
print("是什么错误呢")
else:
# 没有错误时会运行
words = contents.split()
# 方法spilt()以空格为分隔符将字符串拆分成多个部分,并将这些部分都存储在一个列表中;
for ele in words:
print(ele)
num_words = len(words)
print(num_words)
print(f"The file {filename} has about {num_words} words.")
# 后面还可以加上:
finally:
# 不管发生错误与否都会运行
print("不管发生错误与否都会运行")
filenames = ["生于忧患.txt", "出师表.txt", "远方.txt"]
for ele in filenames:
count_words(ele)