python怎么统计txt文件的字数-Python教程

资源魔 31 0

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文件的字数的具体内容,更多请存眷资源魔其它相干文章!

标签: python教程 python编程 python使用问题 python怎么统计txt字数

抱歉,评论功能暂时关闭!