0

所以我有一个程序,它接受一个字符串,并返回一个元组,其中字符串中的所有字母都按排序顺序排列。

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

到目前为止,我有:

_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 文件中获取。

4

1 回答 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)

因为这样您就不需要每次都显式地测试密钥。

于 2013-03-25T17:56:21.113 回答