How to Count Words in Python

You can count the number of words by following these steps:

  1. Split the text content into a list of words.
  2. Iterate through the list of words and count the occurrences of each word.

Here is a sample code for counting the number of words in a text.

def count_words(text):
    # 将文本内容转换为小写,并去除标点符号
    text = text.lower()
    text = ''.join(e for e in text if e.isalnum() or e.isspace())
    
    # 分割文本内容为单词列表
    words = text.split()
    
    # 统计每个单词的出现次数
    word_count = {}
    for word in words:
        if word in word_count:
            word_count[word] += 1
        else:
            word_count[word] = 1
    
    return word_count

text = "Python is a popular programming language. Python is used in various fields including web development, data science, and machine learning."
result = count_words(text)
print(result)

By running the above code, you will get the output of each word and its frequency of occurrence.

bannerAds