字符串列表中最常用词的 Python 程序


当需要在字符串列表中查找最频繁出现的单词时,将迭代该列表并使用“max”方法获取最高字符串的计数。

范例

以下是对上述说明的演示

from collections import defaultdict
my_list = ["python is best for coders", "python is fun", "python is easy to learn"]

print("The list is :")
print(my_list)

my_temp = defaultdict(int)

for sub in my_list:
   for word in sub.split():
      my_temp[word] += 1

result = max(my_temp, key=my_temp.get)

print("The word that has the maximum frequency :")
print(result)

输出

The list is :
['python is best for coders', 'python is fun', 'python is easy to learn']
The word that has the maximum frequency :
python

说明

  • 将必需的包导入到环境中。

  • 定义了一个字符串列表并显示在控制台上。

  • 创建一个整数字典并将其分配给一个变量。

  • 遍历字符串列表,并根据空格进行分割。

  • 确定每个单词的计数。

  • 使用“max”方法确定这些值的最大值。

  • 将其分配给一个变量。

  • 将其显示为控制台的输出。

更新时间:2021-09-16

4K+ 查看次数

开启你的 职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.