To count the number of words in a txt file in Python, you can use the rstrip function and the len function.
The following counts the number of words in White Night Walk.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.')
Result:
The file 白夜行.txt has about 487761 words.
For more Python-related technical articles, please visit Python Tutorialcolumn for learning!
The above is the detailed content of How to count the number of words in a txt file in python. For more information, please follow other related articles on the PHP Chinese website!