要得到一段文本中出现频率最高的20个单词,你可以使用Python编程语言来实现这个任务。以下是一个简单的示例代码,它使用了Python的内置库collections
中的Counter
类来统计单词频率,并使用heapq
库来获取频率最高的20个单词。
import re
from collections import Counter
import heapq
def get_top_n_words(text, n=20):
# 使用正则表达式移除标点符号并将文本转换为小写
words = re.findall(r'\w+', text.lower())
# 计算每个单词的出现频率
word_counts = Counter(words)
# 获取出现频率最高的n个单词
top_n_words = heapq.nlargest(n, word_counts.items(), key=lambda item: item[1])
return top_n_words
# 示例文本
text = """
Your large text goes here. This is an example text to demonstrate the function.
"""
# 获取频率最高的20个单词
top_20_words = get_top_n_words(text)
# 打印结果
for word, frequency in top_20_words:
print(f"{word}: {frequency}")
heapq
模块中的一个函数,用于找出可迭代对象中最大的n个元素。Counter
可以快速统计出所有单词的出现次数。nlargest
函数可以轻松获取任意数量的最高频单词。通过上述方法,你可以有效地得到一段文本中出现频率最高的20个单词及其频率。
领取专属 10元无门槛券
手把手带您无忧上云