您好,我有一个数据框,我想从以这些短语开头或包含这些短语的每一行中删除一组特定的字符“fwd”、“re”、“RE”。我面临的问题是我不知道如何为每种情况应用正则表达式。
我的数据框如下所示:
summary
0 Fwd: Please look at the attached documents and take action
1 NSN for the ones who care
2 News for all team members
3 Fwd:RE:Re: Please take action on the action needed items
4 Fix all the mistakes please
5 Fwd:Re: Take action on the attachments in this email
6 Fwd:RE: Action is required
我想要一个像这样的结果数据框:
summary
0 Please look at the attached documents and take action
1 NSN for the ones who care
2 News for all team members
3 Please take action on the action needed items
4 Fix all the mistakes please
5 Take action on the attachments in this email
6 Action is required
为了摆脱“Fwd”,我使用了 df['msg'].str.replace(r'^Fwd: ','')
最佳答案
如果它们可以位于字符串中的任何位置,则可以使用重复模式:
^(?:(?:Fwd|R[eE]):)+\s*
^
字符串开头(?:
非捕获组(?:Fwd|R[eE]):
匹配 Fwd、Re 或 RE
)+
关闭非捕获组并重复 1+ 次\s*
匹配尾随空格
在替换中使用空字符串。
如果您想匹配所有可能的变体,您还可以使用 re.IGNORECASE
使模式不区分大小写,并使用 (?:fwd|re)
。
例如
str.replace(r'^(?:(?:Fwd|R[eE]):)+\s*','')
关于python - 如何对数据框列上的多个短语应用正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60229899/