Python – 字符串中的词频
pythonserver side programmingprogramming更新于 2025/10/20 19:24:17
当需要使用字符串简写查找单词的频率时,可以使用字典理解。
示例
下面是相同的演示
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’的数量,并将其分配给一个变量。
此变量作为输出显示在控制台上。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

