python实现词频统计
时间: 2023-06-23 10:08:51 浏览: 112
可以使用Python中的collections模块中的Counter函数来实现词频统计。
以下是一个简单的示例代码:
```python
from collections import Counter
# 定义要统计词频的文本
text = "Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, and a syntax that allows programmers to express concepts in fewer lines of code than might be possible in languages such as C++ or Java."
# 将文本转换为单词列表
words = text.split()
# 使用Counter函数进行词频统计
word_count = Counter(words)
# 输出统计结果
print(word_count)
```
输出:
```
Counter({'programming': 2, 'Python': 2, 'in': 2, 'code': 2, 'is': 1, 'an': 1, 'interpreted': 1, 'high-level': 1, 'language': 1, 'for': 1, 'general-purpose': 1, 'Created': 1, 'by': 1, 'Guido': 1, 'van': 1, 'Rossum': 1, 'and': 1, 'first': 1, 'released': 1, '1991,': 1, 'has': 1, 'a': 1, 'design': 1, 'philosophy': 1, 'that': 1, 'emphasizes': 1, 'readability,': 1, 'syntax': 1, 'allows': 1, 'programmers': 1, 'to': 1, 'express': 1, 'concepts': 1, 'fewer': 1, 'lines': 1, 'of': 1, 'than': 1, 'might': 1, 'be': 1, 'possible': 1, 'languages': 1, 'such': 1, 'as': 1, 'C++': 1, 'or': 1, 'Java.': 1})
```
该代码将文本转换为单词列表,然后使用Counter函数进行词频统计,并输出结果。
阅读全文