python教程:python怎么统计txt文件的字数

 所属分类:php教程

 浏览:177次-  评论: 0次-  更新时间:2022-09-28
描述:更多教程资料进入php教程获得。 程序员必备接口测试调试工具:立即使用 Apipost = Postman + Swagger + Mock + Jmeter Api...
更多教程资料进入php教程获得。

程序员必备接口测试调试工具:立即使用
Apipost = Postman + Swagger + Mock + Jmeter
Api设计、调试、文档、自动化测试工具
后端、前端、测试,同时在线协作,内容实时同步

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文件的字数的详细内容,更多请关注zzsucai.com其它相关文章!

积分说明:注册即送10金币,每日签到可获得更多金币,成为VIP会员可免金币下载! 充值积分充值会员更多说明»

讨论这个素材(0)回答他人问题或分享使用心得奖励金币

〒_〒 居然一个评论都没有……

表情  文明上网,理性发言!