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中文網其他相關文章!