【问题标题】:Create a dict whose value is the set of all possible anagrams for a given word创建一个字典,其值是给定单词的所有可能字谜的集合
【发布时间】:2014-12-24 12:56:51
【问题描述】:

所以我想做的是创建一个字典:

  • key 是排序后的单词,
  • value 是每个字谜的集合(由字谜程序生成)。

当我运行我的程序时,我得到了 Ex。单词:{('w','o','r','d')} 不是单词:dorw,wrdo,rowd。文本文件只包含很多单词,每行一个。

代码:

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()

【问题讨论】:

  • s = "word" {s: [{"".join(tup) } for tup in (permutations(s, len(s)))]}

标签: python anagram


【解决方案1】:

您正在为文件中的每个单词创建元组:

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

这将对所有字谜进行排序,创建重复的排序字符元组。

如果您想跟踪所有可能的单词,您应该在此处生成元组。只需阅读以下文字:

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

并使用您的 lengthWord() 函数处理这些单词;此函数确实需要将wordList 值作为参数:

def lengthWord(wordList):
    # ...

你需要从main()传递它:

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

【讨论】:

    猜你喜欢
    • 2014-08-06
    • 2011-09-07
    • 1970-01-01
    • 2016-12-21
    • 2016-06-14
    • 2016-02-01
    • 2017-02-17
    • 2013-12-29
    • 1970-01-01
    相关资源
    最近更新 更多