可以使用Python的Counter类来实现词频统计。以下是一个示例代码:
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}")运行以上代码,输出的结果将会是每个单词及其对应的词频。例如:
This: 1is: 1a: 1sample: 1text.: 1It: 1contains: 1some: 1words: 1that: 1will: 1be: 1counted.: 1注意,这个示例代码没有进行任何文本处理(如词干提取、去除停用词等),仅仅是简单地按空格拆分文本并统计词频。如果需要更复杂的文本处理,可以使用正则表达式或其他库来实现。

