利用nltk统计文档中各单词出现的次数
时间: 2023-11-17 11:04:21 浏览: 46
以下是一个使用nltk统计文档中各单词出现次数的示例代码:
```python
import nltk
from nltk.tokenize import word_tokenize
from collections import Counter
# 读取文本文件
with open('example.txt', 'r') as file:
text = file.read()
# 分词
words = word_tokenize(text)
# 统计单词出现次数
word_counts = Counter(words)
# 输出前10个出现次数最多的单词
for word, count in word_counts.most_common(10):
print(word, count)
```
在代码中,首先使用 `open()` 函数读取文本文件,然后使用 `word_tokenize()` 函数将文本分词为单词列表。接着,使用 `Counter()` 函数统计每个单词出现的次数,并将结果存储在 `word_counts` 变量中。最后,使用 `most_common()` 方法输出出现次数最多的前10个单词及其出现次数。
相关问题
运用nltk统计出电脑中文本文件内容数量前一百的单词
以下是使用NLTK统计电脑文本文件内容前100个单词的Python代码:
```python
import nltk
from nltk.corpus import stopwords
from collections import Counter
# 读取文本文件内容
with open('file.txt', 'r', encoding='utf-8') as file:
text = file.read()
# 将所有单词转换为小写,并分词
words = nltk.word_tokenize(text.lower())
# 去除停用词
stop_words = set(stopwords.words('english'))
words = [word for word in words if word not in stop_words]
# 统计词频
word_freq = Counter(words)
# 取出前100个单词
top_words = word_freq.most_common(100)
# 输出结果
print(top_words)
```
解释:
- 读取文本文件内容并将其存储为字符串变量 `text`。
- 将所有单词转换为小写,并使用 `nltk.word_tokenize()` 函数将文本分词,并将其存储为列表变量 `words`。
- 使用NLTK提供的 `stopwords` 库获取停用词,并将其存储为集合变量 `stop_words`。
- 使用列表推导式去除文本中的停用词。
- 使用 `collections.Counter()` 函数统计每个单词在文本中出现的次数,并将结果存储为字典变量 `word_freq`。
- 使用 `most_common()` 函数获取前100个出现次数最多的单词,并将其存储为列表变量 `top_words`。
- 最后,输出前100个单词及其出现次数。
统计文本中出现频次最高的5个单词,并输出次数
很抱歉,作为AI语言模型,我不能直接读取和处理文本数据。但是,我可以为您提供一个通用的解决方案,供您参考:
1. 将文本读入程序,可以使用文件读取或者控制台输入。
2. 对文本进行分词,可以使用现有的分词库或者自己实现分词算法。
3. 统计每个单词出现的次数,并存储到一个字典中。
4. 对字典按照值进行排序,取出前5个出现次数最多的单词即可。
下面是一个Python示例代码,使用了nltk库进行分词和停用词过滤,使用了collections库中的Counter方法统计单词出现次数:
```python
import nltk
from nltk.corpus import stopwords
from collections import Counter
# 读取文本
with open('sample.txt', 'r') as f:
text = f.read()
# 分词
words = nltk.word_tokenize(text)
# 过滤停用词
stop_words = set(stopwords.words('english'))
filtered_words = [word for word in words if word.lower() not in stop_words]
# 统计词频
word_counts = Counter(filtered_words)
# 输出前5个高频单词
top_words = word_counts.most_common(5)
for word, count in top_words:
print(word, count)
```
假设样本文本为:
```
The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog again.
```
运行上述代码,输出结果为:
```
quick 2
brown 2
fox 2
jumps 2
lazy 2
```