问题
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)
you didn't close the open brace in
input()
method.I suggest using
raw_input()
instead of usinginput()
while dealing with strings.you should use the
classname.method()
if you have imported only the class (in your caseimport difflib
) so usedifflib.get_close_matches(string,list,n)
instead.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