python词汇表生成
时间: 2023-10-14 20:29:52 浏览: 72
以下是一个简单的 Python 代码,用于生成一个单词列表:
```
words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "honeydew", "kiwi", "lemon"]
with open("wordlist.txt", "w") as f:
for word in words:
f.write(word + "\n")
```
这个代码将把单词列表写入名为 "wordlist.txt" 的文本文件中,每个单词占一行。你可以根据需要修改单词列表,并将文件名替换为你想要的任何名称。
相关问题
python生成词汇表
在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个单词的词汇表。
python生成中文词汇表
可以使用Python的jieba库来生成中文词汇表。下面是一个简单的示例代码:
```python
import jieba
# 读取文本文件
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用jieba库进行分词
words = jieba.lcut(text)
# 去除停用词,例如:的、了、是等等
stopwords = ['的', '了', '是', '在', '和', '有', '不', '中', '等', '一种', '一样', '这个']
words = [word for word in words if word not in stopwords]
# 统计词频
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
# 按照词频从高到低排序
sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
# 输出前100个高频词
for i in range(100):
print(sorted_word_counts[i][0], sorted_word_counts[i][1])
```
在该示例代码中,我们首先使用`jieba.lcut()`函数对文本进行分词,然后使用列表推导式去除停用词。接着,使用字典统计每个单词出现的次数,并使用`sorted()`函数按照词频从高到低排序。最后,输出前100个高频词及其出现次数。
注意:在使用jieba库之前,需要先安装该库。可以使用`pip install jieba`命令进行安装。