3 回答

TA貢獻1811條經驗 獲得超4個贊
casefold
將字符串轉換為小寫,并且您的參考字符串包含大寫字符。
作為一個簡單的修復,您可以將“Davids house”更改為“davids house”等。
從長遠來看,您可能希望實現稍微不那么脆弱的比較,但這是一項艱巨的任務,并且取決于您的程序將如何使用以及解析失敗的后果是什么。

TA貢獻1794條經驗 獲得超8個贊
對于拼寫錯誤糾正和支持用戶做破壞測試的事情,下面是一個使用字符串相似性比較來確定輸入是否接近任何用戶名的示例:
import difflib
# Storing the names and directions of users:?
#This is called a dictionary. More info here https://www.w3schools.com/python/python_dictionaries.asp
directions= {
? ? "David": "Directions to David's home from T... \n East on X, \n South on Y.," \
? ? ? ? ? ? " \n West on Z., \n South on A., \n first white house on the right.",
? ? "Caroline": "Directions to Caroline's home from T... \n East on x, \n South on y.," \
? ? ? ? " \n East on z., \n South on p., \n East on q," \
? ? ? ? " \n West on t., \n last brick house in the cul-de-sac.",
? ? "William":"Directions to Will's home from T... \n East on x, \n South on y.," \
? ? ? ? " \n West on z., \n South on Fa., \n West on b., \n first house on the right.",
? ? "Bannon":"<Insert directions to Bannon's house>"
}
# User gives a specific name and then receives a location:
while True:
? ? destination = input("Where would you like to go? ")
? ? highest = 0 #highest score between the user name and input
? ? user_key = "" #name of the user who most closely matches the input
? ? for user in directions: #iterate through all the user's names in the directions dictionary
? ? ? similarity = difflib.SequenceMatcher( #for each user's name, compare it to the input
? ? ? ? ? None, destination, user).ratio()
? ? ? if(similarity > highest): #if the similarity score is greater than the highest recorded score, update the score
? ? ? ? highest = similarity
? ? ? ? user_key = user
? ??
? ? #Code that runs if a match is too low are not found
? ? if(highest < 0.5): #adjust this based on how close you want the match to be. highest will always be between 0.0 and 1.0
? ? ? print("Sorry, that location wasn't found! Please try again.")
? ? ? continue
? ? #Print user's directions
? ? else:
? ? ? print('\n\nGetting directions to ' + user_key + '\'s house\n\n')
? ? ? print(directions[user_key] + "\n\n\n")
因此,如果您輸入“William's house”、“William”、“William's house”、“Williamm”或接近“William”的名稱,您將獲得前往 William 家的路線。

TA貢獻1827條經驗 獲得超8個贊
最小化程序并測試!您發布的代碼多于演示問題所需的代碼。一旦出現if destination.casefold() == 'Davids house':無法正常工作的情況,請盡量減少罐裝數據的問題
destination = "david's house"
if not destination.casefold() == "Davids house":
print(repr(destination), "failed")
這打印
"david's house" failed
幫助casefold說Return a version of the string suitable for caseless comparisons. . 啊,就是這樣。你需要把兩邊都折疊起來。然后是那個討厭的撇號。也許您需要更多規范化,例如擺脫非字母字符。
通過最小化,您為代碼編寫了一個很好的測試。您可以編寫一個小的比較函數來執行 casefold 和其他規范化。然后,您可以對該函數編寫十幾個測試來測試所有邊緣情況。
添加回答
舉報