此時此代碼從用戶處獲取一個字符串,並將其與存儲多個單詞的文本文件進行比較。然後將包含完全匹配的所有單詞輸出到字符串。 (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