python - 根据字典的值获取键
问题描述
第一次练习python,就遇到了这个疑惑。使用可变文本,我输入了一个小段落并根据空格将其拆分。所以现在我有了那段的单词,但这是存储在字典中的。接下来,我继续查找段落中每个单词的出现次数。我的最终动机是制作一个出现超过“x”次的单词的新列表。
我的代码是:
text = '''Population refers to the number of individuals in a particular
place. It could be the number of humans or any other life form living in a
certain specified area. The number of tigers living in a forest is
therefore referred to as the population of tigers in the forest. The
number of people living in a town or city or an entire country is the
human population in that particular area.'''
words = text.split(" ")
a = dict()
for word in words:
if word not in a:
a[word] = 1
else:
a[word]+= 1
newlist = list()
val = 7
for key,value in a.items():
if a[key]>val:
newlist.append(i)
执行最后一行后我收到的最终输出是:
['years.', 'years.', 'years.', 'years.']
我不知道我哪里错了
解决方案
为了创建一个以单词为键、出现次数为值的字典,您需要首先获取所有唯一单词。你可以通过使用set
Python 的函数来做到这一点。
然后,您遍历该集合并使用 的count
方法list
,您可以获得每个单词的出现次数。
你可以在下面看到:
text = '''Population refers to the number of individuals in a particular
place. It could be the number of humans or any other life form living in a
certain specified area. The number of tigers living in a forest is
therefore referred to as the population of tigers in the forest. The
number of people living in a town or city or an entire country is the
human population in that particular area.'''
words = text.split() # Split text and create a list of all words
wordset = set(words) # Get all unique words
wordDict = dict((word,words.count(word)) for word in wordset) # Create dictionary of words and number of occurences.
for key, value in wordDict.items():
print(key + ' : ' + str(value))
这会给你:
individuals : 1
forest : 1
the : 5
could : 1
therefore : 1
place. : 1
form : 1
or : 3
country : 1
population : 2
humans : 1
The : 2
city : 1
living : 3
Population : 1
life : 1
in : 6
a : 4
refers : 1
tigers : 2
is : 2
to : 2
be : 1
an : 1
other : 1
as : 1
particular : 2
number : 4
human : 1
It : 1
any : 1
forest. : 1
town : 1
that : 1
certain : 1
of : 5
entire : 1
people : 1
specified : 1
referred : 1
area. : 2
然后,您可以应用自己的过滤器来获取所有出现x
多次的单词。
推荐阅读
- excel - 使用 PowerPoint VBA 检查 Excel 中的数据
- javascript - 我如何重构代码,使用一个函数代替 4 个函数,每个函数都使用一个特殊的 `useState` 钩子(即 `setAlfaIsTrue(newValue)`)
- c - 字符没有被正确复制
- excel - 数据透视表“无效的过程调用或参数”
- c# - 如何部分匹配(开始)元组字符串?
- sql-server - odbc 上的 sql server 查询获取错误 - [Microsoft] [ODBC Driver Manager] 游标状态无效 0
- python - 两列匹配列表的两个元素
- node.js - 我可以在启动 Angular 通用服务器后更新 index.html 吗?
- android - Android x折叠工具栏字体系列无法更改
- javascript - 从多个 MongoDB 行程中返回一个数组到用户集合