用Python编写代码,练习jieba分词包的使用,对.txt进行分词,并将词频数位于前100的词语统计输出
时间: 2023-06-20 19:07:35 浏览: 103
好的,以下是代码示例:
```python
import jieba
from collections import Counter
# 打开文件,读取文本内容
with open('example.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用jieba分词,得到分词结果列表
word_list = jieba.lcut(text)
# 使用Counter统计词频,并取前100个
word_freq = Counter(word_list).most_common(100)
# 输出结果
for word, freq in word_freq:
print(word, freq)
```
其中,`jieba.lcut()`函数将文本内容分词得到一个列表。`Counter()`函数用于统计列表中各元素出现的次数,返回一个字典。`most_common(100)`方法用于取出前100个出现次数最多的元素。
如果要将结果保存到文件中,可以在最后添加如下代码:
```python
# 将结果保存到文件中
with open('result.txt', 'w', encoding='utf-8') as f:
for word, freq in word_freq:
f.write(word + ' ' + str(freq) + '\n')
```
相关问题
用Python编写代码,练习jieba分词包的使用,对.txt进行分词,并将词频数与词语保存到文件中
好的,我可以帮您写一个示例代码来练习jieba分词包的使用,以下是代码:
```python
import jieba
# 打开文本文件
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 对文本进行分词
words = jieba.cut(text)
# 统计词频
word_dict = {}
for word in words:
if len(word) > 1: # 只统计长度大于1的词语
if word not in word_dict:
word_dict[word] = 1
else:
word_dict[word] += 1
# 将词频数与词语保存到文件中
with open('word_count.txt', 'w', encoding='utf-8') as f:
for word, count in word_dict.items():
f.write(word + ' ' + str(count) + '\n')
```
在这个示例代码中,我们首先打开一个文本文件,并读取其中的文本内容。然后,我们使用jieba分词包对文本进行分词,得到一个词语列表。接着,我们遍历这个词语列表,统计每个词语出现的次数,并将统计结果保存到一个字典word_dict中。最后,我们将这个字典中的词频数与词语保存到一个文本文件word_count.txt中。
需要注意的是,为了避免统计过多的无意义词语,我们在统计过程中只统计了长度大于1的词语。当然,这个条件可以根据实际情况进行修改。
用jieba库对文档 nove.txt 的文本内容进行分词,词频统计的结果排序输出到 result.csv 中
好的,下面是针对您的要求的代码示例:
```python
import jieba
from collections import Counter
import csv
# 读取文本文件
with open("nove.txt", "r", encoding="utf-8") as f:
text = f.read()
# 使用jieba分词
words = jieba.cut(text)
# 统计词频
word_count = Counter(words)
# 将词频统计结果排序,并写入csv文件中
with open("result.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerow(["word", "count"])
for word, count in word_count.most_common():
writer.writerow([word, count])
```
执行完上述代码后,会在当前目录下生成一个名为"result.csv"的文件,文件中包含了对文档"nove.txt"进行分词后的词频统计结果,按照词频从高到低排序。
阅读全文
相关推荐
















