Python-文件与异常-统计文本的单词数

filename = "Happiness.txt"

try:(with open里面不能写encoding=utf-8否则会报错)
    with open(filename) as f_obg:
        contents= f_obg.read()
except FileNotFoundError as e:
    msg = "Sorry,the file"+filename+" does not exits"
    print(msg)
else:
    #计算文件包含的单词数
    words = contents.split()
    num_words = len(words)
    print("The file "+filename+" has about "+str(num_words)+" words")
代码运行结果:
发布了98 篇原创文章 · 获赞 34 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_42133768/article/details/95342823
今日推荐