difflib.get_close_匹配项如果第一个答案是

2024-10-04 01:36:06 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我上一个问题here的更新版本。我在代码中添加了这样一个代码,如果get-chu-close-matches的名字不是他们想要的人的名字,那么放弃最接近的匹配项,重新运行函数并获取第二个最接近的匹配项(现在是第一个,因为函数会抛出第一个匹配项)。在

你有什么意见可以写得更好吗?还有工作。>;>

以下是我目前所掌握的情况:

def throwout(pickedName):
    employeeNames.remove(pickedName)
    pickedName = difflib.get_close_matches(userEmpName, employeeNames, 1)
    print(pickedName)
    userNameOK = input("Is this the name of the person you're looking for?\n\n Type 'Y' or 'N'.\n\n")



employeeNames = ['Colton','Jayne','Barb','Carlene','Dick','Despina']


employeeNames.sort()


userEmpName = input("Please enter the employee name you're searching for. We'll return the best match on record.")


pickedName = difflib.get_close_matches(userEmpName, employeeNames, 1)
print(pickedName)


userNameOK = input("Is this the name of the person you're looking for?\n\n Type 'Y' or 'N'.\n\n")


if userNameOK == "N" or "n":
    if pickedName in employeeNames:
        throwout(pickedName)
    else:
        break
else:
    break

列表中的名称用完时出错:

^{pr2}$

我理解这意味着,由于名称列表中没有更多的名称可以删除它们,那么全局变量“userAnswer”就没有定义了。在


Tags: orthenamere名称youforclose
1条回答
网友
1楼 · 发布于 2024-10-04 01:36:06

不需要创建函数来抛出列表中的名称,因为list.remove(name)在一行中执行相同的操作。在

import difflib

employeeNames = ['Colton','Coltron','Colty','Jayne','Barb','Carlene','Dick','Despina']
employeeNames.sort()
userEmpName = raw_input("Please enter the employee name you're searching for. We'll return the best match on record.")

while True:
    global Answer
    pickedName = difflib.get_close_matches(userEmpName, employeeNames, 1)

    print(pickedName)
    print employeeNames

    if len(pickedName)==0:
        break

    userNameOK = raw_input("Is this the name of the person you're looking for?\n\n Type 'Y' or 'N'.\n\n")

    if (userNameOK=='n' or userNameOK=='N'):
        employeeNames.remove(pickedName[0])

    else:
        Answer=pickedName[0]
        break

print Answer+" is the right choice"

但是,使用全局变量通常是不好的做法,因此您可以创建一个函数来完成所有这些操作并返回正确的Answer

另外,由于employeeNames在每次从中删除一个名称时都会被修改,因此最好创建一个列表的副本并处理该特定列表

相关问题 更多 >