问题描述
我的列表中包含诸如[‘orange’,‘cool’,‘app’....]
之类的单词,我想从DataFrame的描述列中输出所有这些确切的完整单词(如果有)。
我还附带了带有代码的示例图片。我使用了str.findall()
,如图所示,它从add
提取了additional
,从app
提取了apple
。但是,我不希望那样。仅在与整个单词匹配时才输出。
解决方法
您可以使用修改代码
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)
快。