免责声明:我才刚刚开始学习 Python
我有一个函数,可以计算一个单词在文本文件中出现的次数,并将该单词设置为键,将计数设置为值,并将其存储在字典“book_index”中。这是我的代码:
alice = open('location of the file', 'r', encoding = "cp1252")
def book_index(alice):
"""Alice is a file reference"""
"""Alice is opened, nothing else is done"""
worddict = {}
line = 0
for ln in alice:
words = ln.split()
for wd in words:
if wd not in worddict:
worddict[wd] = 1 #if wd is not in worddict, increase the count for that word to 1
else:
worddict[wd] = worddict[wd] + 1 #if wd IS in worddict, increase the count for that word BY 1
line = line + 1
return(worddict)
我需要将字典“翻个底朝天”,并使用计数作为键,将任何出现 x 次的单词作为值。例如:[2, 'hello', 'hi'] 其中 'hello' 和 'hi' 在文本文件中出现了两次。
我需要循环遍历我现有的字典还是再次循环遍历文本文件?
最佳答案
由于字典是值映射的键,因此您无法有效地按值进行过滤。因此,您将必须遍历字典中的所有元素以获取值具有特定值的键。
这将打印出字典 d
中值等于 searchValue
的所有键:
for k, v in d.items():
if v == searchValue:
print(k)
关于您的 book_index
函数,请注意您可以使用内置的 Counter
用于计数。 Counter 本质上是一个字典,它将计数作为其值并自动处理不存在的键。使用计数器,您的代码将如下所示:
from collections import Counter
def book_index(alice):
worddict = Counter()
for ln in alice:
worddict.update(ln.split())
return worddict
或者,正如 roippi 在对另一个答案的评论中建议的那样,只需 worddict = Counter(word for line in alice for word in line.split())
。
关于python - 如何翻字典 "inside-out",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19962586/