Python – 字符串速记中的词频
有时在处理Python字符串时,我们可能会遇到需要提取字符串中所有单词的频率的问题。这个问题早已经解决了。这讨论了解决这个问题的速记,因为它在许多领域都有应用,从 Web 开发和竞争性编程。让我们讨论一些可以解决这个问题的方法。
Input : test_str = ‘Gfg is best’
Output : {‘Gfg’: 1, ‘is’: 1, ‘best’: 1}
Input : test_str = ‘Gfg Gfg Gfg’
Output : {‘Gfg’: 3}
方法 #1:使用字典理解 + count() + split()
上述功能的组合可以用来解决这个问题。在此,我们首先拆分所有单词,然后使用 count() 对它们进行计数。
# Python3 code to demonstrate working of
# Words Frequency in String Shorthands
# Using dictionary comprehension + count() + split()
# initializing string
test_str = 'Gfg is best . Geeks are good and Geeks like Gfg'
# printing original string
print("The original string is : " + str(test_str))
# Words Frequency in String Shorthands
# Using dictionary comprehension + count() + split()
res = {key: test_str.count(key) for key in test_str.split()}
# printing result
print("The words frequency : " + str(res))
The original string is : Gfg is best . Geeks are good and Geeks like Gfg
The words frequency : {‘Gfg’: 2, ‘is’: 1, ‘best’: 1, ‘.’: 1, ‘Geeks’: 2, ‘are’: 1, ‘good’: 1, ‘and’: 1, ‘like’: 1}
方法 #2:使用Counter() + split()
上述方法的组合也可以用来解决这个问题。在此,我们使用 Counter() 执行计数任务,并使用 split() 执行单词分离任务。
# Python3 code to demonstrate working of
# Words Frequency in String Shorthands
# Using Counter() + split()
from collections import Counter
# initializing string
test_str = 'Gfg is best . Geeks are good and Geeks like Gfg'
# printing original string
print("The original string is : " + str(test_str))
# Words Frequency in String Shorthands
# Using Counter() + split()
res = Counter(test_str.split())
# printing result
print("The words frequency : " + str(dict(res)))
The original string is : Gfg is best . Geeks are good and Geeks like Gfg
The words frequency : {‘Gfg’: 2, ‘is’: 1, ‘best’: 1, ‘.’: 1, ‘Geeks’: 2, ‘are’: 1, ‘good’: 1, ‘and’: 1, ‘like’: 1}