python怎么统计txt文件的字数
时间:2019-08-01 10:37来源:PHP中文网 作者:猪哥 点击:
次
Python中要统计txt文件字数可以rstrip函数和len函数进行。 如下统计白夜行.txt的字数: file_name = 白夜行.txttry: with open(file_name, encoding=utf8) as file_obj: #由于书名不是英文,要加上 encoding=utf8 contents = file_obj.read()except FileNotF
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.
|
(责任编辑:yang) |
织梦二维码生成器
------分隔线----------------------------