【发布时间】: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