python - 数据框中的动态正则表达式
问题描述
具有如下数据框:
df= pd.DataFrame({'category':['Fishing','Refrigeration','store'],'synonyms_text':['seafood','foodlocker',' food']})
清单如下:
list_desc=['FOOD', 'GROWERS', 'INTERNATIONAL']
如何迭代list_desc
以创建要在数据框中使用的动态正则表达式?
for word in list_desc:
print(word.lower())
df_tmp= df.loc[df['synonyms_text'].str.contains(r'\bfood\b')]
wherefood
必须用word
变量替换。
谢谢
解决方案
您可以使用format()
like in动态构建您的正则表达式r'\b{0}\b'.format(word)
例子:
for word in list_desc:
df_tmp= df.loc[df['synonyms_text'].str.contains(r'\b{0}\b'.format(re.escape(word.lower())))]
更多信息:如何在正则表达式中使用变量?
推荐阅读
- android - Json 异常:应为 BEGIN_OBJECT 但为 BEGIN_ARRAY
- javascript - 获取 Intercom User_Id 并作为 javascript 变量传递
- redirect - 无法将 www 页面添加到 google adsense
- java - 未找到 Maven 资源
- javascript - 使用 JSON 文件中的数据动态创建元素
- excel - VBA将字母表中的列值转换为数字
- php - Internet Explorer 11 向 Laravel 后端发送格式不正确的日期
- javascript - 输入类型=时间显示错误的时区
- javascript - react-naitve 组件“RNCamera”重新注册冒泡事件“topPictureTaken”作为直接事件模块ConstantsForComponent
- java - maven cxf-codegen-plugin XMLStreamException 出错:属性限制