写一个关于词频统计的代码
时间: 2023-12-01 19:13:22 浏览: 28
好的,下面是一个简单的Python代码,用于统计一段文本中每个单词出现的次数。
```python
text = "This is a sample text with several words. We want to count how many times each word appears in this text."
# 将所有单词转换为小写,并使用空格将文本分割成单词列表
words = text.lower().split()
# 创建一个空字典用于存储单词及其出现次数
word_counts = {}
# 遍历单词列表,统计每个单词出现的次数
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
# 输出结果
for word, count in word_counts.items():
print(f"{word}: {count}")
```
这个代码会输出以下结果:
```
this: 1
is: 1
a: 1
sample: 1
text: 2
with: 1
several: 1
words.: 1
we: 1
want: 1
to: 1
count: 1
how: 1
many: 1
times: 1
each: 1
word: 2
appears: 1
in: 1
```
这个代码通过遍历文本中的单词列表,使用一个字典来记录每个单词出现的次数。遍历完成后,输出每个单词及其出现的次数。