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计算中文文件字数_python怎么统计txt文件的字数的全部内容,更多相关python计算中文文件字数_python怎么统计txt文件内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复