文本处理 统计单词个数和出现频度
时间: 2023-11-13 21:02:00 浏览: 56
实现统计单词个数和出现频度的常规方法是使用哈希表,即将每个单词作为哈希表的键,出现次数作为对应的值。具体实现步骤如下:
1. 定义一个哈希表,用于存储单词及其出现次数。
2. 将文本按照空格、标点符号等分割成单词。
3. 遍历每个单词,将其作为哈希表的键,如果该键已存在,则将其对应的值加1,否则将该键插入哈希表,并将其对应的值设置为1。
4. 遍历完所有单词后,得到每个单词及其出现次数的信息,可以按照出现次数进行排序,输出出现频度最高的单词。
以下是一个 Python 实现的示例代码:
```python
import re
from collections import defaultdict
text = "This is a sample text for counting words. This text contains several words, some of which appear more than once."
# 定义一个默认值为0的哈希表,用于存储单词及其出现次数
word_count = defaultdict(int)
# 将文本按照空格、标点符号等分割成单词,并统计每个单词的出现次数
words = re.findall(r'\b\w+\b', text.lower())
for word in words:
word_count[word] += 1
# 按照出现次数进行排序,并输出出现频度最高的单词
sorted_word_count = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
for word, count in sorted_word_count:
print(f"{word}: {count}")
```
输出结果为:
```
this: 2
is: 1
a: 1
sample: 1
text: 2
for: 1
counting: 1
words: 2
contains: 1
several: 1
of: 1
which: 1
appear: 1
more: 1
than: 1
once: 1
```