0

这是我以前的问题here的更新版本。我正在添加到代码中,如果 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”是未定义的。

4

1 回答 1

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每次从名称中删除名称时都会修改它应该更好地创建列表的副本并处理该特定列表

于 2014-02-03T13:04:12.913 回答