jieba库分词词频统计保存的结果从哪里找
时间: 2023-11-11 20:05:08 浏览: 38
jieba库分词词频统计可以使用Python中的字典数据结构来保存,也可以将结果保存到文件中。如果是保存到字典中,可以直接使用Python的字典操作获取。如果是保存到文件中,可以使用Python的文件操作打开文件并读取。具体方法如下:
1. 保存到字典中
```python
import jieba
text = "我爱自然语言处理技术"
words = jieba.lcut(text)
freq_dict = {}
for word in words:
if word in freq_dict:
freq_dict[word] += 1
else:
freq_dict[word] = 1
print(freq_dict) # 输出结果为 {'我': 1, '爱': 1, '自然语言处理': 1, '技术': 1}
```
2. 保存到文件中
```python
import jieba
text = "我爱自然语言处理技术"
words = jieba.lcut(text)
freq_dict = {}
for word in words:
if word in freq_dict:
freq_dict[word] += 1
else:
freq_dict[word] = 1
with open('freq.txt', 'w') as f:
for word, freq in freq_dict.items():
f.write(word + '\t' + str(freq) + '\n')
```
在上述代码中,我们将词频统计结果保存到了名为 `freq.txt` 的文件中,每行一个词和其出现次数,用制表符 `\t` 分隔。如果需要读取该文件,可以使用类似下面的代码:
```python
with open('freq.txt', 'r') as f:
for line in f:
word, freq = line.strip().split('\t')
print(word, freq)
```
其中,`strip()` 方法用于去除行末的换行符,`split('\t')` 方法用于按制表符分隔词和频率。