分词txt如何统计词频代码
时间: 2023-06-02 20:05:37 浏览: 58
以下是Python代码示例:
```
from collections import Counter
import jieba
# 读取文本文件
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用jieba分词
words = jieba.lcut(text)
# 统计词频
word_counts = Counter(words)
# 输出前10个高频词
for word, count in word_counts.most_common(10):
print(word, count)
```
在这个代码示例中,我们使用了jieba库来进行中文分词,并使用Counter类来统计词频。其中,text.txt为需要统计词频的文本文件,可以自行修改。在输出高频词时,使用了most_common函数,并将参数设置为10,意味着输出前10个高频词。
相关问题
利用jieba对txt进行分词统计词频
好的,首先需要安装jieba库,可以使用以下命令进行安装:
```
pip install jieba
```
安装完成后,我们可以按照以下步骤进行分词:
1. 读取txt文件中的文本内容
2. 使用jieba库对文本内容进行分词
3. 统计每个词出现的次数
下面是示例代码:
```python
import jieba
# 读取txt文件内容
with open('example.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 对文本进行分词
words = jieba.lcut(text)
# 统计词频
freq = {}
for word in words:
if len(word) > 1: # 只统计长度大于1的词
freq[word] = freq.get(word, 0) + 1
# 按照词频从大到小排序
freq_list = sorted(freq.items(), key=lambda x: x[1], reverse=True)
# 输出前10个出现频率最高的词
for i in range(10):
print(freq_list[i][0], freq_list[i][1])
```
上述示例代码中,我们通过`jieba.lcut()`函数对文本进行分词,并将结果保存到`words`列表中。接着,我们使用一个字典`freq`来统计词频,字典的键为词,值为该词出现的次数。注意,我们只统计长度大于1的词,以避免统计到一些无意义的单个字符。最后,我们使用`sorted()`函数将字典转换成一个按照词频从大到小排序的列表`freq_list`,并输出前10个出现频率最高的词及其出现次数。
jieba统计词频代码
下面是使用jieba库统计词频的示例代码:
```python
import jieba
from collections import Counter
# 打开文件并读取内容
with open('sample.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 使用jieba分词
words = jieba.cut(content)
# 统计词频
word_count = Counter(words)
# 输出词频统计结果
for word, count in word_count.most_common():
print(word, count)
```
其中,`sample.txt`是需要统计词频的文本文件。使用`jieba.cut`函数对文本进行分词,得到分词后的词语列表。然后使用`collections.Counter`函数统计每个词语出现的次数。最后使用`most_common`方法将词频从高到低排列,并输出每个词语及其出现次数。