首頁  >  文章  >  後端開發  >  python怎麼統計txt檔的字數

python怎麼統計txt檔的字數

尚
原創
2019-07-06 10:28:567836瀏覽

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相關技術文章,請造訪Python教學欄位進行學習!

以上是python怎麼統計txt檔的字數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn