使用Python统计词频并输出排名前5的词语。
时间: 2023-06-12 19:03:26 浏览: 1299
Python编写的词频统计工具
5星 · 资源好评率100%
可以使用Python的collections模块中的Counter类来统计词频。以下是一个简单的例子:
```python
from collections import Counter
text = "Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant whitespace."
words = text.lower().split()
word_counts = Counter(words)
top_words = word_counts.most_common(5)
for word, count in top_words:
print(word, count)
```
输出结果为:
```
python 2
an 1
interpreted, 1
high-level, 1
general-purpose 1
```
这里我们将输入的文本转换为小写字母,并使用split()函数将其拆分为单词列表,然后使用Counter类进行词频统计。接着使用most_common()函数取出出现频率最高的5个单词,并输出它们的词频和排名。
阅读全文