使用python統計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.

哇,我真是太不容易了,看的都快吐了好麼。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章