在 Python 中,可以使用字典(dict)来实现单词出现频率的统计。具体步骤如下:
将原始文本转换为单词列表,可以使用字符串的 split() 方法将文本分割为单词列表,例如:
text = "this is a sample text to test word frequency"
words = text.split()
创建一个空的字典,用于存储单词出现的次数:
word_count = {}
遍历单词列表,对每个单词进行统计:
for word in words:
if w```ord in word_
word_count[word] += 1
else:
word_count[word] = 1
找出出现次数最多的单词,可以使用 max() 函数和字典的 items() 方法来实现:
max_word = max(word_count.items(), key=lambda x: x[1])[0]
上述代码中,word_count.items() 返回一个由字典键值对组成的列表,max() 函数接受一个可迭代对象和一个关键字函数,并返回可迭代对象中的最大值。key=lambda x: x[1] 指定了按照字典的值进行比较,最终返回的是键值对中值最大的键。
最终代码如下:
text = "this is a sample text to test word frequency"
words = text.split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
max_word = max(word_count.items(), key=lambda x: x[1])[0]
print("出现频率最高的单词是:", max_word)
以上代码的输出结果为:出现频率最高的单词是:to。