python怎么统计txt文件的字数


本文摘自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 3.9

Python有这么强大吗

Python3 pandas 读取mysql数据和插入

js两个日期比较相差多少天实例

numpy实现合并多维矩阵、list的扩展方法

Python中tornado的路由解析(附实例)

Python质数如何判断

Python界面是什么样的

Python语言依赖平台吗

pandas技巧之 详解dataframe中的apply与applymap方法

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...