Python – 列出字符串中的单词频率
给定一个单词列表,将每个单词的出现频率映射到字符串中。
Input : test_str = ‘geeksforgeeks is best for geeks and best for CS’, count_list = [‘best’, ‘geeksforgeeks’, ‘computer’]
Output : [2, 1, 0]
Explanation : best has 2 occ., geeksforgeeks 1 and computer is not present in string.
Input : test_str = ‘geeksforgeeks is best for geeks and best for CS’, count_list = [‘better’, ‘gfg’, ‘computer’]
Output : [0, 0, 0]
Explanation : No word from list present in string.
方法 #1:使用 defaultdict() + 循环 + 列表推导
在此,我们使用 loop + defaultdict() 计算单词频率,然后使用列表推导获取与单词列表对应的所有计数。
Python3
# Python3 code to demonstrate working of
# Divide String into Equal K chunks
# Using list comprehension
from collections import defaultdict
# initializing strings
test_str = 'geeksforgeeks is best for geeks and best for CS'
# printing original string
print("The original string is : " + str(test_str))
# initializing count_list
count_list = ['best', 'geeksforgeeks', 'computer', 'better', 'for', 'and']
# computing frequency
res = defaultdict(int)
for sub in test_str.split():
res[sub] += 1
# assigning to list words
res = [res[sub] for sub in count_list]
# printing result
print("The list words frequency : " + str(res))
Python3
# Python3 code to demonstrate working of
# Divide String into Equal K chunks
# Using list comprehension
from collections import Counter
# initializing strings
test_str = 'geeksforgeeks is best for geeks and best for CS'
# printing original string
print("The original string is : " + str(test_str))
# initializing count_list
count_list = ['best', 'geeksforgeeks', 'computer', 'better', 'for', 'and']
# computing frequency using Counter()
res = Counter(test_str.split())
# assigning to list words
res = [res[sub] for sub in count_list]
# printing result
print("The list words frequency : " + str(res))
输出
The original string is : geeksforgeeks is best for geeks and best for CS
The list words frequency : [2, 1, 0, 0, 2, 1]
方法 #2:使用 Counter() + 列表推导
在此,Counter() 用于执行计算频率的任务,然后,列表理解用于为列表单词分配频率。
Python3
# Python3 code to demonstrate working of
# Divide String into Equal K chunks
# Using list comprehension
from collections import Counter
# initializing strings
test_str = 'geeksforgeeks is best for geeks and best for CS'
# printing original string
print("The original string is : " + str(test_str))
# initializing count_list
count_list = ['best', 'geeksforgeeks', 'computer', 'better', 'for', 'and']
# computing frequency using Counter()
res = Counter(test_str.split())
# assigning to list words
res = [res[sub] for sub in count_list]
# printing result
print("The list words frequency : " + str(res))
输出
The original string is : geeksforgeeks is best for geeks and best for CS
The list words frequency : [2, 1, 0, 0, 2, 1]