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统计txt文件字数的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!