如果 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))]
最佳答案
像()
这样的括号是正则表达式中的特殊字符,因此您需要在它们之前使用反斜杠\
,例如:
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)
关于python - NLP:如何搜索带有括号的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61647158/