词频统计python完整代码
时间: 2024-06-21 17:01:48 浏览: 17
词频统计是文本处理中常见的任务,Python中的`collections`库提供了方便的`Counter`类来计算字符串中各个元素(在这个场景下通常是单词)的出现次数。以下是一个简单的词频统计完整代码示例:
```python
from collections import Counter
def word_frequency(text):
# 将文本转换为小写并分割成单词列表
words = text.lower().split()
# 使用Counter计算每个单词的频率
word_counts = Counter(words)
return word_counts
# 示例文本
text = "This is a sample text for word frequency analysis. It will be used to demonstrate how the code works."
word_freq = word_frequency(text)
# 打印前10个最常见的单词及其频率
for word, freq in word_freq.most_common(10):
print(f"{word}: {freq}")
相关问题
文本词频统计python代码
在Python中,我们可以使用内置的collections模块中的Counter类来轻松地进行文本词频统计。以下是一个简单的例子:
```python
from collections import Counter
# 假设我们有一个字符串或文本列表
text = "这是一个简单的例子,我们将演示如何使用Python进行文本词频统计。这个例子会重复一些单词,比如Python和统计。"
# 首先,我们需要将文本分割成单词列表
words = text.split()
# 使用Counter计算每个单词出现的频率
word_counts = Counter(words)
# 打印出单词及其频率
for word, count in word_counts.items():
print(f"{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
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)