difflib.get_close_matches扔出去名称列表中,如果第一个答案是不正确的(dif

2019-10-29 12:48发布

下面是从我前面的问题的更新版本在这里 。 我加入到代码中,如果get_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

错误运行了在列表中的名称:

Traceback (most recent call last):
  File "C:/Python33/employee1.py", line 64, in <module>
    print(userAnswer + " is the right choice.\n")
NameError: global name 'userAnswer' is not defined

据我所知,意味着因为名字的名单是消除他们根本没有更多的名字,全局变量“userAnswer”然后不确定的。

Answer 1:

有没有必要创建一个函数,从列表,扔出去的名字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修改每一个名称被删除时,从它应该是更好地创建列表的副本和特定列表上工作



文章来源: difflib.get_close_matches throw out names in a list if first answer isn't correct