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文件的字数的详细内容,更多请关注php中文网其它相关文章!
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
程序员必备接口测试调试工具:点击使用
Apipost = Postman + Swagger + Mock + Jmeter
Api设计、调试、文档、自动化测试工具
网页生成APP,用做网站的技术去做APP:立即创建
手机网站开发APP、自助封装APP、200+原生模块、2000+映射JS接口按需打包
相关文章
相关视频