difflib.get_close_matches() - 帮助获得所需的结果

时间:2014-02-01 04:46:24

标签: python list sorting difflib

程序的基本要点是从员工名称列表开始,然后对其进行排序。等待用户输入“end”以停止填充名称列表(我有100个名字,我将其缩短为例子)。之后,用户可以输入员工姓名,程序将运行difflib.get_close_matches()。

这是问题所在;我收到了get_close_matches的语法错误。我应该如何以不同的方式输入difflib?也;如果您有任何提高代码效率的技巧,请说明如何以及为什么它更有效。我对Python很缺乏经验,所以要温柔,嗯?

示例代码:

import difflib
employeeNames = ['Colton','Jayne','Barb','Carlene','Dick','Despina']
employeeNames.sort()
endInput = input('Type "end" to view list of names.\n\n')
if endInput == "end":
    userEmpName = input("Please enter the employee name you're searching for. We'll return the best match on record."
get_close_matches(userEmpName, employeeNames, 1)

1 个答案:

答案 0 :(得分:0)

您的代码有语法错误: 将此代码与您的代码匹配:

import difflib
employeeNames = ['Colton','Jayne','Barb','Carlene','Dick','Despina']
employeeNames.sort()
endInput = raw_input('Type "end" to view list of names.\n\n')
if endInput == "end":
    userEmpName = raw_input("Please enter the employee name you're searching for. We'll return the best match on record.")
    print difflib.get_close_matches(userEmpName, employeeNames, 1)
  1. 您未使用input()方法关闭左大括号。

  2. 我建议在处理字符串时使用raw_input()而不是input()

  3. 如果您只导入了课程classname.method(),则应使用import difflib,因此请改用difflib.get_close_matches(string,list,n)

  4. 您需要在返回值之前使用print语句。

  5. get_close_matches()也应在if内调用,因为endInput!='end' NameErroruserEmpName {/ 1}}。

    修改

    我应该问你关于你的python翻译版本 打印行应该使用这样的大括号。


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

    原因是python 2.x打印是statement(正如我在4点提到的那样),但在python 3.x中它是function