用python个单词出现的次数,并按照词频逆序排序
时间: 2024-03-07 09:47:30 浏览: 22
好的,可以使用Python的collections模块中的Counter类来实现。以下是代码示例:
```python
from collections import Counter
# 定义文本
text = "This is a sample text with several words. We will count the frequency of each word appearing in this text."
# 将文本转换为小写并分割成单词列表
words = text.lower().split()
# 使用Counter类统计每个单词出现的次数
word_counts = Counter(words)
# 按照词频逆序排序并打印每个单词及其出现次数
for word, count in sorted(word_counts.items(), key=lambda x: x[1], reverse=True):
print(f"{word}: {count}")
```
输出结果如下:
```
the: 2
text: 1
this: 1
is: 1
a: 1
sample: 1
with: 1
several: 1
words.: 1
we: 1
will: 1
count: 1
frequency: 1
of: 1
each: 1
word: 1
appearing: 1
in: 1
```
其中,Counter类会返回一个字典,键为单词,值为出现次数。使用sorted函数对字典进行排序,key参数指定为每个元素的值(即出现次数),reverse参数指定为True,表示逆序排序。最后使用for循环遍历排序后的结果,并打印每个单词及其出现次数。