【发布时间】:2020-11-16 07:27:08
【问题描述】:
我的清单
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(',')
匹配有问题,但是由于列表前面没有空格,所以我要找的'apple'包含在'pineapple'中,所以匹配了。
再举一个例子,我正在寻找“葡萄”,但白葡萄中含有葡萄,所以这也算在内。
如何在列表中每个索引的开头留一个空格?
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
【问题讨论】:
-
Ieatpineapple...Ilovebanana,这种情况很难 -
正则表达式中的单词边界(实际上是两个)可能会有所帮助:
\b但其中一些文本无法识别。 -
@YOBEN_S 如果文字之间有空格会不会一样?编辑内容
-
@MichaelButscher 即使在句子中的单词之间应用空格也很难移动吗?请看上面的修改内容。
标签: python python-3.x regex pandas