您好,欢迎来到五一七教育网。
搜索
您的当前位置:首页python怎么统计txt文件的字数

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教程栏目进行学习!

Copyright © 2019- 517ttc.cn 版权所有 赣ICP备2024042791号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务