Home >Backend Development >Python Tutorial >How to count the number of words in a txt file in python

How to count the number of words in a txt file in python

尚
Original
2019-07-06 10:28:567935browse

How to count the number of words in a txt file in python

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn