列表到正则表达式,包括前导空格

2024-04-28 13:51:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我的名单

mylist = [apple, banana, grape]
df

text
I love banana
apple is delicious
I eat pineapple
hate whitegrape

要匹配文本中包含列表的内容,请执行以下操作

mylist = [f"(?i){re.escape(k.lower())}" for k in mylist]
extracted = df['text'].str.lower().str.findall(f'({"|".join(mylist)})').apply(set)
df['matching'] = extracted.str.join(',')

匹配有一个问题,但由于列表前面没有空格,我要找的“苹果”包含在“菠萝”中,所以它匹配

作为另一个例子,我在寻找“葡萄”,但葡萄包含在白葡萄中,所以这也是计算

如何在列表中每个索引的开头留出一个空格

result above
text                 matching
I love banana        banana
apple is delicious   apple
I eat pineapple      apple
hate whitegrape      grape

结果是我想要的

text                 matching
I love banana        banana
apple is delicious   apple
I eat pineapple  
hate whitegrape 

Tags: textappledf列表isbananamatchingstr
2条回答

然后你可以做split

df.text.str.lower().str.split().apply(lambda x : [y for y in x if y in mylist]).str[0]
Out[227]: 
0    banana
1     apple
2       NaN
3       NaN
Name: text, dtype: object

更新为str.findall

df.text.str.lower().str.findall(r'\b({0})\b'.format('|'.join(mylist)))
Out[248]: 
0    [banana]
1     [apple]
2          []
3          []
Name: text, dtype: object

您可以使用:

 df.text.str.extract(f"(?i)\\b({'|'.join(mylist)})\\b")
        0
0  banana
1   apple
2     NaN
3     NaN

当然,您可以根据您的示例将extract更改为findall

相关问题 更多 >