中文词频统计python代码
时间: 2023-07-23 15:30:39 浏览: 48
以下是一个简单的中文词频统计 Python 代码:
```python
import jieba
# 打开文件
with open('input.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 切分文本
words = jieba.cut(text)
# 计算词频
word_counts = {}
for word in words:
if len(word) > 1:
word_counts[word] = word_counts.get(word, 0) + 1
# 按词频排序
sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
# 输出结果
for word, count in sorted_word_counts:
print(word, count)
```
解释:
1. 导入 jieba 库,用于中文分词。
2. 打开文件,并读取文本内容。
3. 利用 jieba.cut() 函数将文本切分成词语。
4. 遍历词语,统计每个词语出现的次数,保存在字典 word_counts 中。
5. 利用 sorted() 函数按照词频从大到小排序。
6. 遍历排序后的结果,输出每个词语和它的词频。
相关问题
python 实现中文词频统计 源代码
当然可以,以下是一个简单的 Python 代码:
```
import jieba
from collections import Counter
# 将文本读入内存
with open('input.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用 jieba 分词
words = list(jieba.cut(text))
# 统计词频并排序
freq_dict = Counter(words)
sorted_freq_dict = sorted(freq_dict.items(), key=lambda x: x[1], reverse=True)
# 输出前 10 个词及其出现次数
for word, freq in sorted_freq_dict[:10]:
print(word, freq)
```
注意,这里使用了 jieba 库进行中文分词。你可以将上面的代码保存为一个.py 文件并在命令行中运行,前提是已经安装了 jieba 库。
词频统计python
词频统计是指统计一段文本中各个单词出现的频率。在Python中,可以使用不同的方法进行词频统计。以下是几种常见的方法:
1. 原始字典自写代码统计:
```python
wordcount = {}
for word in all_words:
wordcount[word] = wordcount.get(word, 0) + 1
sorted_wordcount = sorted(wordcount.items(), key=lambda x: x[1], reverse=True)
```
2. 使用第三方库jieba进行中文词频统计:
```python
import jieba
from collections import Counter
wordcount = Counter()
for word in jieba.cut(text):
if len(word) > 1 and word not in stop_words:
wordcount[word] += 1
sorted_wordcount = wordcount.most_common(10)
```
3. 使用原生API进行英文词频统计:
```python
speech = speech_text.lower().split()
wordcount = {}
for word in speech:
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
sorted_wordcount = sorted(wordcount.items(), key=lambda x: x[1], reverse=True)[:10]
```