在Python的DataFrame的描述栏中查找确切的单词

问题描述

我的列表中包含诸如[‘orange’,‘cool’,‘app’....]之类的单词,我想从DataFrame的描述列中输出所有这些确切的完整单词(如果有)。

我还附带了带有代码的示例图片。我使用了str.findall(),如图所示,它从add提取additional,从app提取apple。但是,我不希望那样。仅在与整个单词匹配时才输出

enter image description here

解决方法

您可以使用修改代码

df['exactmatch'] = df['text'].str.findall(fr"\b({'|'.join(list1)})\b").str.join(",")

或者,如果您的list1单词中可以包含特殊字符,

df['exactmatch'] = df['text'].str.findall(fr"(?<!\w)({'|'.join(map(re.escape,list1))})(?!\w)").str.join(",")

fr"\b({'|'.join(list1)})\b"fr"(?<!\w)({'|'.join(map(re.escape,list1))})(?!\w)"创建的模式看起来像

\b(orange|cool|app)\b
(?<!\w)(orange|cool|app)(?!\w)

请参见regex demo。注意.str.join(",")被认为比.apply(",".join)快。