字符串列表中最常用词的 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”方法确定这些值的最大值。
将其分配给一个变量。
将其显示为控制台的输出。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP