python生成词汇表
时间: 2023-10-13 07:28:52 浏览: 193
在Python中,生成词汇表可以使用collections模块中的Counter类。具体步骤如下:
1. 导入Counter类
```python
from collections import Counter
```
2. 定义一个字符串或列表
```python
text = "This is a sample text for generating vocabulary"
# 或者
text_list = ["This", "is", "a", "sample", "text", "for", "generating", "vocabulary"]
```
3. 使用Counter类对字符串或列表进行计数
```python
word_count = Counter(text.split())
# 或者
word_count = Counter(text_list)
```
4. 获取前n个出现频率最高的单词
```python
top_n_words = word_count.most_common(n)
```
完整代码示例:
```python
from collections import Counter
text = "This is a sample text for generating vocabulary"
word_count = Counter(text.split())
top_n_words = word_count.most_common(5)
print(top_n_words)
```
输出:
```
[('a', 1), ('for', 1), ('generating', 1), ('is', 1), ('sample', 1)]
```
这里生成了一个包含出现频率最高的5个单词的词汇表。
阅读全文
相关推荐


















