regex 从Pandas列中删除不同的字符串模式

m3eecexj  于 2022-12-27  发布在  其他
关注(0)|答案(2)|浏览(113)

我有以下列,其中包括电子邮件主题标题:

Subject
EXT || Transport enquiry
EXT || RE: EXTERNAL: RE: 0001 || Copy of enquiry
EXT || FW: Model - Jan
SV: [EXTERNAL] Calculations

我想要达到的是:

Subject
Transport enquiry
0001 || Copy of enquiry
Model - Jan
Calculations

为此,我使用下面的代码,它只考虑了我传递的第一个正则表达式,而忽略了其余的

def clean_subject_prelim(text):
     text = re.sub(r'^EXT \|\| $' , '' , text)
     text = re.sub(r'EXT \|\| RE: EXTERNAL: RE:', '' , text)
     text = re.sub(r'EXT \|\| FW:', '' , text)
     text = re.sub(r'^SV: \[EXTERNAL]$' , '' , text)
     return text
df['subject_clean'] = df['Subject'].apply(lambda x: clean_subject_prelim(x))

为什么这行不通,我错过了什么?

dxxyhpgq

dxxyhpgq1#

您可以使用

pattern = r"""(?mx)  # MULTILINE mode on
^                   # start of string
(?:                 # non-capturing group start
   EXT\s*\|\|\s*(?:RE:\s*EXTERNAL:\s*RE:|FW:)? # EXT || or EXT || RE: EXTERNAL: RE: or EXT || FW:
 |                  # or
   SV:\s*\[EXTERNAL]# SV: [EXTERNAL]
)                   # non-capturing group end
\s*                 # zero or more whitespaces
"""
df['subject_clean'] = df['Subject'].str.replace(pattern', '', regex=True)

请参见regex demo
因为使用了re.X(?x)),所以应该转义文本空格和#字符,或者只使用\s*\s+来匹配零个/一个或多个空格。

bvjxkvbb

bvjxkvbb2#

去掉第一个表达式中的$符号,并将一些正则表达式从位置切换过来,如下所示:

import pandas as pd
import re

def clean_subject_prelim(text):
     text = re.sub(r'EXT \|\| RE: EXTERNAL: RE:', '' , text)
     text = re.sub(r'EXT \|\| FW:', '' , text)
     text = re.sub(r'^EXT \|\|' , '' , text)
     text = re.sub(r'^SV: \[EXTERNAL]' , '' , text)
     return text

data = {"Subject": [
"EXT || Transport enquiry",
"EXT || RE: EXTERNAL: RE: 0001 || Copy of enquiry",
"EXT || FW: Model - Jan",
"SV: [EXTERNAL] Calculations"]}

df = pd.DataFrame(data)
df['subject_clean'] = df['Subject'].apply(lambda x: clean_subject_prelim(x))

相关问题