使用元组和字典的字谜查找器
我有一个程序,它可以接收一个字符串,然后返回一个元组,里面是这个字符串中所有字母按顺序排列的结果。
接下来,这个程序需要创建一个字典,字典的键是这些元组,而值则是所有包含这些键的单词列表。
到目前为止,我已经有了:
_DEBUG = True
def getLetters(string):
"""Purpose, to nab letters from a string and to put them in a tuple in
sorted order."""
#sort the letters and put them in a tuple
tuple_o_letters = tuple(sorted(string))
if _DEBUG:
print tuple_o_letters
return tuple_o_letters
def main():
try:# open the file
fin = open("words2.txt")
except:
#if file doesn't exist
print("no, no, file no here.")
sys.exit(0)
wordList = [] #create a word list
for eachline in fin:
#fill up the word list and get rid of new lines
wordList.append(eachline.strip())
word_dict = {} # create a dictionary
for eachWord in wordList:
tuple = getLetters(eachWord) # make a tuple out of each word
word_dict[tuple] = wordList #store it into a dictionary
print word_dict #print out the dictionary
if __name__ == '__main__':
main()
现在,虽然我可以把元组当作字典的键来存储,但我搞不清楚怎么把单词列表作为值存储,前提是这些单词列表必须包含这些键。
举个例子:如果字典中有一个键是 ('d', 'o', 'g'),那么我希望这个键对应的值能是单词 god 和 dog,前提是这两个单词在单词列表中(这些单词是从 words2.txt 文件中获取的)。
1 个回答
0
你现在存储的是完整的单词列表。你想要存储的是每组字母组合对应的匹配单词:
word_dict = {} # create a dictionary
for eachWord in wordList:
key = getLetters(eachWord) # make a tuple out of each word
if key in word_dict:
word_dict[key].append(eachWord)
else:
word_dict[key] = [eachWord]
这段代码会为给定的键(字母组合)创建一个列表,如果这个键还不存在的话;如果已经存在,就直接把单词加到这个列表里。
你可以通过使用collections.defaultdict
来简化这个过程:
from collections import defaultdict
word_dict = defaultdict(list)
for eachWord in wordList:
word_dict[getLetters(eachWord)].append(eachWord)
这样的话,你就不需要每次都去检查这个键是否存在了。