在nlp_lab下,编写Python代码,从给定的文本文件中统计出最常出现的三个单词(英文单词长度大于等于5)。
时间: 2024-09-06 21:03:08 浏览: 30
要在`nlp_lab`目录下编写Python代码以统计最长的三个英文单词,我们可以使用`nltk`库进行文本处理,包括分词和去除停用词。以下是一个简单的示例:
```python
import nltk
from nltk.corpus import stopwords
from collections import Counter
# 加载必要的资源
nltk.download('punkt')
nltk.download('stopwords')
def top_three_words(file_path):
with open(file_path, 'r') as file:
text = file.read().lower()
# 分词
words = nltk.word_tokenize(text)
# 删除停用词
stop_words = set(stopwords.words('english'))
filtered_words = [word for word in words if word.isalpha() and len(word) >= 5 and word not in stop_words]
# 统计并获取最常见的三个单词
word_counts = Counter(filtered_words).most_common(3)
return word_counts
# 使用文件路径替换'nlp_lab/your_text_file.txt'
top_words = top_three_words('nlp_lab/your_text_file.txt')
for word, count in top_words:
print(f"'{word}': {count} times")
```
这段代码会读取指定的文本文件,对其进行分词、移除停用词(长度小于5的单词和非字母字符),然后计算并返回最常见的三个单词及其出现次数。