Reputation: 151
def get_name(string, list_names):
"""
Inputs:
string: a string to be analyzed
list_names: a list of names among whom we are looking for
"""
for name in list_names:
begin_pattern = re.compile("^\name")
if begin_pattern.search(string):
return name
Hi I need search for names which I have in the string. My list is
list_names = ['LaMarcus Aldridge',
'Damian Lillard',
'Wesley Matthews',
'Arron Afflalo',
'Robin Lopez',
'Nicolas Batum',
'Chris Kaman']
function returns no error but also it returns no matches at all. get_name("Damian Lillard makes 18-foot jumper (Allen Crabbe assists)", list_names)
it should return Damian Lillard. Can you help me. Thanks
Upvotes: 0
Views: 7821
Reputation: 561
It is possible to use a simple if x in y
, where it then checks if x
exists in y
. And if the string contains more than 1 of the names, you would need it to return a list
of names. It is possible to use list comprehension like this:
def get_name(string, list_names):
return [name for name in list_names if name in string]
Here is the same function without using list comprehension:
def get_name(string, list_names):
results = []
for name in list_names:
if name in string:
results.append(name)
return results
Upvotes: 1
Reputation: 367
Edit: I'm adding code in the spirit of what you want; ignore my original code.
def get_name(string,list_names):
for name in list_names:
if string.startswith(name):
print(name)
list_names = ['LaMarcus Aldridge',
'Damian Lillard',
'Wesley Matthews',
'Arron Afflalo',
'Robin Lopez',
'Nicolas Batum',
'Chris Kaman']
get_name("Damian Lillard makes 18-foot jumper (Allen Crabbe assists)", list_names)
Returns Damian Lillard. Or, if you wanted LaMarcus Aldridge, rather than changing your script, you'd use:
get_name("LaMarcus Aldridge makes 18-foot jumper (Allen Crabbe assists)", list_names)
According to your original question,
def get_name(string, list_names):
for player in list_names:
if player==string:
return player
list_names = ['LaMarcus Aldridge',
'Damian Lillard',
'Wesley Matthews',
'Arron Afflalo',
'Robin Lopez',
'Nicolas Batum',
'Chris Kaman']
get_name('Damian Lillard', list_names)
Upvotes: 1
Reputation: 563
Try this :
import re
def get_name(string, list_names):
for name in list_names:
match = re.search(r'\b%s\b'%(name),string)
if match:
return name
string ="Damian Lillard makes 18-foot jumper (Allen Crabbe assists)"
list_names = ['LaMarcus Aldridge','Damian Lillard','Wesley Matthews','Arron Afflalo','Robin Lopez','Nicolas Batum','Chris Kaman']
print(get_name(string,list_names))
Upvotes: 0