使用元组和词典的anagram finder

时间:2013-03-25 17:51:05

标签: python dictionary tuples

所以我有一个带字符串的程序,并按字母顺序返回一个元组中所有字母的元组。

程序然后需要创建一个字典,将元组作为键,值为列出所有带键的单词

到目前为止,我有:

_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'),我会得到值为神和狗的特定条目,假设这两个单词在单词列表中(从words2.txt文件。

1 个答案:

答案 0 :(得分: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)

因为那时你不需要每次都明确地测试密钥。