NLP:如何搜索有括号的字符串?

问题描述 投票:1回答:1

我试图过滤一个数据框,如果col1包含一个列表中的任何子串。问题是有一个子串包含了括号,导致了一个错误(图中的粗体字)。有什么解决办法吗?谢谢!我正在尝试过滤一个数据框,如果col1包含列表中的任何子串,就会导致错误(图中为粗体)。

index   fruit_name
0       "apple"
1       "pear"
2       "passionfruit (Passiflora)"
4       "grape"

substring_list = ['apple',**'(passiflora)'**]
df[df.fruit_name.str.contains('|'.join(substring_list))]
python string pandas nlp contains
1个回答
2
投票

大括号,如 () 在regex中是特殊字符,所以你需要使用反斜杠。\ 在他们面前像。

df = pd.DataFrame({'fruit_name': ["apple","pear","passionfruit (Passiflora)", "grape"]})

substring_list = ['apple','\(passiflora\)']
print (df[df.fruit_name.str.contains('|'.join(substring_list), case=False)]) 
                  fruit_name
0                      apple
2  passionfruit (Passiflora)
© www.soinside.com 2019 - 2024. All rights reserved.