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
您好我需要搜索字符串中的名称。我的清单是
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)
应该让Damian Lillard回归。你能帮助我吗。感谢
答案 0 :(得分:1)
编辑:我按照你想要的精神添加代码;忽略我的原始代码。
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)
返回Damian Lillard。或者,如果你想要LaMarcus Aldridge,而不是改变你的剧本,你可以使用:
get_name("LaMarcus Aldridge makes 18-foot jumper (Allen Crabbe assists)", list_names)
根据你原来的问题,
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)
答案 1 :(得分:1)
可以使用简单的if x in y
,然后检查x
中是否存在y
。如果字符串包含多个名称,则需要它返回list
个名称。可以像这样使用列表理解:
def get_name(string, list_names):
return [name for name in list_names if name in string]
这是不使用列表理解的相同功能:
def get_name(string, list_names):
results = []
for name in list_names:
if name in string:
results.append(name)
return results
答案 2 :(得分:0)
试试这个:
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))