为什么我无法搜索我创建的字典(Python)?
在这个程序中,我正在从一个普通的文本文件中制作一个字典。简单来说,我是统计一个单词在文档中出现的次数,这个单词就成为字典的“键”,而它出现的次数就是“值”。我可以创建这个字典,但之后我却无法在字典中进行搜索。以下是我根据大家的建议更新的代码。非常感谢大家的帮助。
from collections import defaultdict
import operator
def readFile(fileHandle):
d = defaultdict(int)
with open(fileHandle, "r") as myfile:
for currline in myfile:
for word in currline.split():
d[word] +=1
return d
def reverseLookup(dictionary, value):
for key in dictionary.keys():
if dictionary[key] == value:
return key
return None
afile = raw_input ("What is the absolute file path: ")
print readFile (afile)
choice = raw_input ("Would you like to (1) Query Word Count (2) Print top words to a new document (3) Exit: ")
if (choice == "1"):
query = raw_input ("What word would like to look up? ")
print reverseLookup(readFile(afile), query)
if (choice == "2"):
f = open("new.txt", "a")
d = dict(int)
for w in text.split():
d[w] += 1
f.write(d)
file.close (f)
if (choice == "3"):
print "The EXIT has HAPPENED"
else:
print "Error"
4 个回答
根据你打算如何使用这个 reverseLookup()
函数,你可能会发现,如果使用两个字典,你的代码会更顺畅。首先像现在这样建立第一个字典,然后再建立一个第二个字典,这个字典用来记录每个单词出现的次数和对应的单词。这样一来,你的 reverseLookup()
函数就不需要在每次查找时都执行 for k in d.keys()
这个循环了。这个循环只需要执行一次,之后的每次查找都会快很多。
我拼凑了一些代码(虽然没有测试过),来展示我所说的内容。我借用了Tim的 readFile()
函数,因为我觉得它看起来更好 :) 但我把他那个局部字典 d
移到了全局,这样可以让函数更简洁。在一个“真正的项目”中,我可能会把整个东西放进一个类里,这样可以在运行时使用任意数量的字典,并且提供合理的封装。这只是演示代码。 :)
import operator
from collections import defaultdict
d = defaultdict(int)
numbers_dict = {}
def readFile(fileHandle):
with open(fileHandle, "r") as myfile:
for currline in myfile:
for word in currline.split():
d[word] +=1
return d
def prepareReverse():
for (k,v) in d.items():
old_list = numbers_dict.get(v, [])
new_list = old_list << k
numbers_dict[v]=new_list
def reverseLookup(v):
numbers_dict[v]
如果你打算进行两次或更多次查找,这段代码会用内存换取执行速度。你只需遍历字典一次(遍历所有元素并不是字典的强项),但代价是内存中会有重复的数据。
你的代码在查看第一个(键,值)对后就返回了。你需要在返回值没有找到之前,先检查整个字典。
def reverseLookup(dictionary, value):
for key in dictionary.keys():
if dictionary[key] == value:
return key
return None
另外,你也不应该返回 "error"
,因为它可能是字典中的一个单词,也就是一个键!
你的方法太复杂了(而且在你发的代码示例中,语法上也有错误)。
另外,你把内置的名字 dict
重新绑定了,这也是个问题。
而且,这个功能在Python中其实已经内置了:
from collections import defaultdict
def readFile(fileHandle):
d = defaultdict(int) # Access to undefined keys creates a entry with value 0
with open(fileHandle, "r") as myfile: # File will automatically be closed
for currline in myfile: # Loop through file line-by-line
for word in currline.strip().split(): # Loop through words w/o CRLF
d[word] +=1 # Increase word counter
return d
至于你的 reverseLookup
函数,可以看看ypercube的回答。