python怎么统计txt文件的字数

发布时间:2022-05-15 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了python怎么统计txt文件的字数脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Python中要统计txt文件字数可以rstrip函数和len函数进行。

如下统计白夜行.txt的字数:

file_name = '白夜行.txt'
try:
    wITh oPEn(file_name, encoding='utf8') as file_obj:
    #由于书名不是英文,要加上 encoding='utf8'
        contents = file_obj.read()
except FileNotFoundError:
    msg = 'Sorry, the file' + file_name + ' does not exist.'
    PRint(msg)
else:
    words = contents.rstrip()
    num_words = len(words)
    print('The file ' + file_name + ' has about ' + str(num_words) + ' words.')

结果:

The file 白夜行.txt has about 487761 words.

更多Python相关技文章,请访问Python教程栏目进行学习!

以上就是python怎么统计txt文件的字数的详细内容,更多请关注脚本宝典其它相关文章!

脚本宝典总结

以上是脚本宝典为你收集整理的python怎么统计txt文件的字数全部内容,希望文章能够帮你解决python怎么统计txt文件的字数所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: