0

これは、以前の質問hereの更新版です。get_close_matches の名前が必要な人の名前ではない場合、最も近い一致を破棄して関数を再実行し、2 番目に近い一致を取得するコードを追加しています (関数がスローするため、最初に最初の試合でアウト)。

これをより良く書く方法について何かコメントはありますか? そして仕事。>.>

これが私がこれまでに持っているものです:

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)同じことを1行で行うように、リストから名前をスローする関数を作成する必要はありません。

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 に答える