词频统计的python代码
时间: 2023-06-02 13:07:40 浏览: 74
Sure, 这是一个简单的词频统计的Python代码:
```python
text = "Hello world, this is a simple text for word count"
words = text.lower().split()
word_count = {}
for word in words:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
print(word_count)
```
以上代码将给出一个单词出现的频率字典。
相关问题
词频统计python代码
以下是一个简单的Python代码用于词频统计:
```python
text = "This is a sample text with several words. This is another sample text with some different words."
# 将所有大写字母转换为小写字母,以便词频统计更加准确
text = text.lower()
# 将文本分割成单词
words = text.split()
# 创建一个空字典来保存每个单词的出现次数
word_count = {}
# 遍历每个单词并统计它们的出现次数
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 按照单词出现次数从高到低对字典进行排序
sorted_word_count = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
# 打印每个单词及其出现次数
for word, count in sorted_word_count:
print(word, count)
```
输出:
```
sample 2
is 2
this 2
with 2
words. 1
several 1
another 1
text 1
some 1
different 1
```
中文词频统计python代码
以下是一个简单的中文词频统计 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. 遍历排序后的结果,输出每个词语和它的词频。