文本词频统计python代码
时间: 2024-06-24 12:00:41 浏览: 17
在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中有许多库可以帮助我们轻松完成这项工作,比如`collections`和`nltk`库。下面是一个简单的例子,使用`collections`库中的`Counter`来统计词频:
```python
from collections import Counter
import re
# 假设这是你的文本字符串
text = "This is a sample text. It contains several words that will be counted. Sample text is used for demonstration purposes."
# 首先,我们需要将文本转换为小写并移除标点符号
text = re.sub(r'[^\w\s]', '', text.lower())
# 使用split函数按空格分割单词
words = text.split()
# 使用Counter计算词频
word_counts = Counter(words)
# 打印最常见的10个单词及其频率
most_common_words = word_counts.most_common(10)
for word, freq in most_common_words:
print(f"{word}: {freq}")
```
文本词频统计python
你好,关于文本词频统计的Python代码,以下是一个简单的示例:
```
# 导入模块
import re
from collections import Counter
# 读取文件
with open('sample.txt', 'r') as f:
contents = f.read()
# 取出单词
words = re.findall(r'\b\w+\b', contents.lower())
# 统计词频
word_counts = Counter(words)
# 输出前十个词频最高的单词
for word, count in word_counts.most_common(10):
print(f'{word}: {count}')
```
希望对您有所帮助!如果您有任何其他问题,请继续提出。