从字符串列表中查找匹配词,return 个匹配词 - Py

Find matching words from a list in a string, return the matching word(s) - Py

我正在编写代码来检查字符串中的单词是否与单词列表匹配。我已经拥有以下完美运行的功能:

def lookup(string,list_of_words):
     if any(i in string for i in list_of_words)==True:
        return 1
     else:
        return 0

但是,现在我希望函数不是 return 0 或 1,而是匹配的单词,ej:

list_of_words=['pencil','eraser','marker']
lookup2('I have a pencil and a pen', list_of_words)
#output: 
'pencil'

我写了下面的代码,但是 return 是错误 NameError: name 'i' is not defined:

def lookup2(string,list_of_words):
    if any(i in string for i in words)==True:
        return i
    else:
        return np.nan

你们知道我怎样才能让它正常工作吗? 谢谢

你可以试试这个:

def lookup2(string,list_of_words):
    return ','.join(j for j in string.split() if j in list_of_words)

本质上,它正在做的是:

  1. 迭代拆分字符串的元素(.split() 方法 returns 列表)
  2. 正在检查 list_of_word
  3. 中是否有任何单词
  4. 通过 ,
  5. 加入
def lookup2(string, list_of_words):
    return set(string.split()).intersection(list_of_words)

list_of_words = ['pencil', 'eraser', 'marker']
print(lookup2('pencil eraser', list_of_words))  # {'pencil', 'eraser'}

您的方法可以通过使用 Python 3.8+ 中可用的 Walrus operator 来实现。

def lookup2(string, list_of_words):
    if any((p:=i) in string for i in list_of_words):  # ==True not needed
        return p                                      # p value maintained from list comprehension
    else:
        return None                                   # None more standard to return for string matching

或更简洁:

def lookup2(string, list_of_words):
    return p if any((p:=i) in string for i in list_of_words) else None

另一个变体:

>>> list_of_words = ['pencil', 'eraser', 'marker']
>>> sentence = 'I have a pencil and a pen'
>>> [word for word in list_of_words if word in sentence]
['pencil']