python怎么统计txt文件的字数

python怎么统计txt文件的字数,第1张

概述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文件的字数所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1156497.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-01
下一篇2022-06-01

发表评论

登录后才能评论

评论列表(0条)

    保存