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

Release: 2019-07-06 10:28:56
Original
7885 people have browsed it

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.')
Copy after login

Result:

The file 白夜行.txt has about 487761 words.
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template