Python - 字符串中的词频
当需要使用字符串速记来求词频时,可以使用字典理解。
示例
下面是相同的演示
my_str = 'Hi there Will, how are you Will, Will you say Hi to me'
print("字符串是: " )
print(my_str)
my_result = {key: my_str.count(key) for key in my_str.split()}
print("词频为: ")
print(my_result)输出结果字符串是:
Hi there Will, how are you Will, Will you say Hi to me
词频为:
{'Hi': 2, 'there': 1, 'Will,': 2, 'how': 1, 'are': 1, 'you': 2, 'Will': 3, 'say': 1, 'to': 1, 'me': 1}解释
定义了一个字符串,并显示在控制台上。
字典理解用于遍历字符串,并根据空格对其进行拆分。
'key'的计数被确定,并被分配给一个变量。
此变量在控制台上显示为输出。