深度阅读

How to Count Words in File To count the number of words in a text file using Python

作者
作者
2023年08月22日
更新时间
16.53 分钟
阅读时间
0
阅读量

To count the number of words in a text file using Python, you can open the file, read its contents, split the contents into individual words, and then count the number of words using a dictionary. Here’s an example:

filename = 'myfile.txt'   # replace with the name of your file

wordcount = {}   # create an empty dictionary to store word counts

with open(filename, 'r') as file:
    # read the contents of the file and split into words
    words = file.read().split()

    # iterate over each word and add to the word count dictionary
    for word in words:
        if word not in wordcount:
            wordcount[word] = 1
        else:
            wordcount[word] += 1

# print out the word count for each word
for word, count in wordcount.items():
    print(word, count)

In this example, we first specify the name of the file to open (filename). We then create an empty dictionary (wordcount) to store the count of each word in the file.

We use a with statement to open the file in read-only mode and read its contents into a variable (words). We then split the contents of the file into individual words using the split() method.

Next, we use a for loop to iterate over each word in the words list. If the word is not already in the wordcount dictionary, we add it to the dictionary with a count of 1. If the word is already in the dictionary, we increment its count by 1.

Finally, we iterate over each key-value pair in the wordcount dictionary and print out the word followed by its count.

In general, this approach can be used to count the frequency of any word or character in a text file using Python.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。