Python 数据帧中的动态正则表达式

Python 数据帧中的动态正则表达式,python,regex,pandas,Python,Regex,Pandas,具有如下数据帧: df= pd.DataFrame({'category':['Fishing','Refrigeration','store'],'synonyms_text':['seafood','foodlocker',' food']}) list_desc=['FOOD', 'GROWERS', 'INTERNATIONAL'] 及下列名单: df= pd.DataFrame({'category':['Fishing','Refrigeration','store'],'syn

具有如下数据帧:

df= pd.DataFrame({'category':['Fishing','Refrigeration','store'],'synonyms_text':['seafood','foodlocker',' food']})
list_desc=['FOOD', 'GROWERS', 'INTERNATIONAL']
及下列名单:

df= pd.DataFrame({'category':['Fishing','Refrigeration','store'],'synonyms_text':['seafood','foodlocker',' food']})
list_desc=['FOOD', 'GROWERS', 'INTERNATIONAL']
如何迭代
列表_desc
以创建要在数据帧中使用的动态正则表达式

for word in list_desc:
    print(word.lower())
    df_tmp= df.loc[df['synonyms_text'].str.contains(r'\bfood\b')]
其中,
食品
必须由
单词
变量代替


谢谢

您可以使用
format()
r'\b{0}\b'.format(word)

例如:

列表描述中的单词的
:
df_tmp=df.loc[df['synonyms_text'].str.contains(r'\b{0}\b'.format(re.escape(word.lower()))]

更多信息:

完美,它成功了。Thanks@JuanPerez,很高兴问题解决了。如果我的回答有帮助,你能接受吗?谢谢:)一旦
单词
包含特殊字符,它就不起作用了。一旦特殊字符出现在单词的开头/结尾,单词边界将停止工作。最好使用
f-string
stringformatting@WiktorStribiżew,将添加re.escape到解决方案中。有很多选项,请注意注意警告。看见