0

该程序的基本要点是从员工姓名列表开始,然后对其进行排序。等待用户输入“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)
4

1 回答 1

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在返回值之前使用语句。

get_close_matches()应该在内部调用,if因为如果endInput!='end'thenNameError会发生userEmpName.

编辑:

我应该问你关于你的 python 解释器版本的问题。
打印行应该使用这样的大括号。


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

原因在python 2.x印刷品中是 a statement(正如我在第 4 点中提到的),但在python 3.x其 afunction中。

于 2014-02-01T05:52:54.093 回答