How to write a code for counting word frequency in Python?

The word frequency can be counted using the Counter class in Python. Below is an example code:

from collections import Counter

# 输入文本
text = "This is a sample text. It contains some words that will be counted."

# 将文本拆分成单词列表
words = text.split()

# 统计词频
word_freq = Counter(words)

# 打印词频结果
for word, freq in word_freq.items():
    print(f"{word}: {freq}")

When you run the code above, the output will be the frequency of each word. For example:

This: 1
is: 1
a: 1
sample: 1
text.: 1
It: 1
contains: 1
some: 1
words: 1
that: 1
will: 1
be: 1
counted.: 1

Please note that this example code does not perform any text processing (such as stemming, removing stopwords, etc.), it simply splits the text by spaces and counts word frequencies. If more complex text processing is needed, regular expressions or other libraries can be used to achieve this.

广告
Closing in 10 seconds
bannerAds