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 和其他规范化。然后,您可以对该函数编写十几个测试来测试所有边缘情况。
添加回答
举报