【问题标题】:Adding anagrams to a dictionary from a .txt file in Python?从 Python 中的 .txt 文件将字谜添加到字典中?
【发布时间】:2015-12-13 23:59:03
【问题描述】:

我有一个文本文件,它是一长串没有空格的单词,例如“neuropsychologicalneuropsychologistneuropsychologyneuropsychopathic”等 我正在尝试构建一个程序,该程序将接受输入的单词并检查 .txt 文件中该单词的任何字谜,然后将它们添加到字典中。

到目前为止,我想出的代码可以打印 1 个字典,其中包含 words.txt 中的 1 个排列;

anagram_dict  = {}

def anagram(word):

    b = open('words.txt', 'r').readlines()
    text = ''.join(line.strip() for line in b)

    #print(len(text))

    for i in range(len(text)-len(word)):
        prop = text[i:i+len(word)]
        if all(char in word for char in prop): #and all(prop.count(char) == prop.count(word) for char in prop):
            anagram_dict[''.join(sorted(word))] = [prop]

    print(anagram_dict)

anagram("demand")

问题是它打印的排列不是字谜(我输入“需求”,期待“疯狂”出来,但它打印文件中的“amamad”,但不是字谜)我怎样才能做到以便它仅在排列是真正的字谜时才打印字典(相同的字母只是重新排列)?

我认为问题可能出在“if all(char in word for char in prop): # and all(prop.count(char) == prop.count(word) for char in prop):”

尤其是被注释掉的部分,因为它在运行时只打印一个空字符串。

抱歉这么久,我只是想确保我解释了自己。感谢您的帮助。

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    all(char in word for char in prop) 只是检查word 的所有字母是否在prop 中。 所有需求信都是"present" in "madden",所以会出现在结果中。

    all(prop.count(char) == prop.count(word) for char in prop) 有问题(可能是错字)。

    应该是all(prop.count(char) == word.count(char) for char in prop)


    还有一个更好的选择,检查propword 的排序版本是否相同。

    sword = ''.join(sorted(word))
    anagram_dict[sword] = []
    for i in range(len(text)-len(word)):
        prop = text[i:i+len(word)]
        if sword == ''.join(sorted(prop)):
            anagram_dict[sword].append(prop)
    

    【讨论】:

    • 非常感谢,它现在可以在一本字典中打印所有排列,但现在我正在尝试让它只将包含在 words.txt 中的排列添加到所述字典中。我认为它可能只是“如果签入 text/b”,但这只是打印带有空值的字典。
    • 在单独的列表中附加字谜。然后在循环结束后,检查该列表是否为空。如果不是,您可以将该列表添加到您的字典中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多