简体   繁体   English

创建一个dict,其值是给定单词所有可能的字谜的集合

[英]Create a dict whose value is the set of all possible anagrams for a given word

So what im trying to do is create a dict whose: 所以我想做的是创建一个dict,

  • key is the word in sorted order and 关键是单词的排序顺序
  • value is the set of each anagram (generated by an anagram program). value是每个字谜的集合(由字谜程序生成)。

When i run my program i get Ex. 当我运行程序时,我得到了Ex。 word : {('w', 'o', 'r', 'd')} not word : dorw, wrdo, rowd. 单词:{('w','o','r','d')}不是单词:dorw,wrdo,rowd。 Text file just contains a lot of words one on each line. 文本文件仅包含很多单词,每行一个。

Code: 码:

def main():
    wordList = readMatrix()
    print(lengthWord())

def readMatrix():
    wordList = []
    strFile = open("words.txt", "r")
    lines = strFile.readlines()
    for line in lines:
        word = sorted(line.rstrip().lower())
        wordList.append(tuple(word))
    return tuple(wordList)

def lengthWord():
    lenWord = 4
    sortDict = {}
    wordList = readMatrix()
    for word in wordList:
        if len(word) == lenWord:
            sortWord = ''.join(sorted(word))
            if sortWord not in sortDict:
                sortDict[sortWord] = set()
            sortDict[sortWord].add(word)
    return sortDict


main()

You are creating tuples of each word in the file: 您正在为文件中的每个单词创建元组:

for line in lines:
    word = sorted(line.rstrip().lower())
    wordList.append(tuple(word))

This will sort all your anagrams, creating duplicate sorted character tuples. 这将对所有字谜进行排序,从而创建重复的排序字符元组。

If you wanted to track all possible words, you should not produce tuples here. 如果你想跟踪所有可能的话,你应该在这里生产的元组。 Just read the words: 只需阅读以下文字:

for line in lines:
    word = line.rstrip().lower()
    wordList.append(word)

and process those words with your lengthWord() function; 并使用您的lengthWord()函数处理这些单词; this function does need to take the wordList value as an argument: 此函数确实需要将wordList值作为参数:

def lengthWord(wordList):
    # ...

and you need to pass that in from main() : 并且您需要从main()传递它:

def main():
    wordList = readMatrix()
    print(lengthWord(wordList))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM