本文摘自php中文网,作者尚,侵删。

Python中要统计txt文件字数可以rstrip函数和len函数进行。
如下统计白夜行.txt的字数:
1 2 3 4 5 6 7 8 9 10 11 12 | 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.' )
|
结果:
1 | The file 白夜行.txt has about 487761 words.
|
更多Python相关技术文章,请访问Python教程栏目进行学习!
以上就是python怎么统计txt文件的字数的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python绘图四叶草
Python语言有哪两种编程方式
Python手动抛出异常怎么处理
microPython能做什么
Python中包是什么?有什么作用?Python中包的介绍
Python怎么安装opencv库
scrapy安装教程 pip 或 conda 两种安装方法.
笨办法学Python怎么样
序列化和反序列化的详细介绍
Python中关于input和raw_input的比较
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python怎么统计txt文件的字数