difflib.get_close_matches() - Help getting desired result

牧云@^-^@ 提交于 2019-12-13 04:42:33

问题


The basic gist of the program is to start with a list of employee names, then sort it. Wait for user to input "end" to stop populating the list of names (I have 100 names, I cut it short for the example). Afterwards, the user can enter an employee name and the program will run difflib.get_close_matches().

Here's the question; I'm getting a syntax error for get_close_matches. How should I be entering the difflib differently? Also; if you have any tips for making the code more efficient, please also state how and why it's more efficient. I'm fairly inexperienced with Python, so be gentle, eh?

EXAMPLE CODE:

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:


Your code has syntax errors: Match this code with yours:

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. you didn't close the open brace in input() method.

  2. I suggest using raw_input() instead of using input() while dealing with strings.

  3. you should use the classname.method() if you have imported only the class (in your case import difflib) so use difflib.get_close_matches(string,list,n) instead.

  4. You need to use print statement before the returned value.

Also get_close_matches() should be called inside of if because if endInput!='end' then NameError will occur for userEmpName.

EDIT:

I should have asked you about your python interpreter version.
The print line should use braces like this.


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

The reason is in python 2.x print is a statement(as I mentioned in 4rth point) but in python 3.x its a function.



来源:https://stackoverflow.com/questions/21494177/difflib-get-close-matches-help-getting-desired-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!