此时此代码从用户处获取一个字符串,并将其与存储多个单词的文本文件进行比较。然后将包含完全匹配的所有单词输出到字符串。 (EG“otp = opt,top,pot)目前,当我输入字符串时,它只匹配字符串与重排顺序中的相同的完全相同的字母。类型超过信件,但仍输出包含的所有单词,例如:键入“orkignwer”,并计划将输出“工作”,即使有多余的字母带字符串的Python字符串
words = []
def isAnAnagram(word, user):
wordList= list(word)
wordList.sort()
inputList= list(user)
inputList.sort()
return (wordList == inputList)
def getAnagrams(user):
lister = [word for word in words if len(word) == len(user) ]
for item in lister:
if isAnAnagram(item, user):
yield item
with open('Dictionary.txt', 'r') as f:
allwords = f.readlines()
f.close()
for x in allwords:
x = x.rstrip()
words.append(x)
inp = 1
while inp != "99":
inp = input("enter word:")
result = getAnagrams(inp)
print(list(result))
您可能想要使用'Counter',然后检查输入单词是否包含所有相同的字母('a.keys()== b.keys()'),并且每个字母的计数较高或相等'b [k]> v for k,v in a.items()'。 –
另外:请记住,使用'with'时不需要关闭文件。 – cdonts