我有一個包含分隔符的字串列,我想創建一個函式來僅為包含分隔符的字串提取子字串
當前的
EMAIL TITLE
[email protected] Marketing Analyst
[email protected] 501.Software Engineer.MG3
[email protected] Product Researcher
[email protected] Managing Director
[email protected] 64.Legal Consultant.I44
[email protected] Hardware Analyst.
我想提取“。”之間的子字串。delimiters 僅適用于帶有分隔符的字串。否則,文本應保持不變。
EMAIL TITLE NEW_TITLE
[email protected] Marketing Analyst Marketing Analyst
[email protected] 501.Software Engineer.MG3 Software Engineer
[email protected] Product Researcher Product Researcher
[email protected] Managing Director Managing Director
[email protected] 64.Legal Consultant.I44 Legal Consultant
[email protected] Hardware Analyst. Hardware Analyst.
我嘗試使用以下代碼創建一個函式,但它似乎不起作用
def clean_title(text):
match = re.search(r"\.(.*?)\.", text)
if match:
return match.group(1)
else:
return text
df['NEW_TITLE'] = df['TITLE'].apply(clean_title)
感謝任何形式的幫助,謝謝!
uj5u.com熱心網友回復:
您可以使用替換方法:
df['NEW_TITLE'] = df['TITLE'].str.replace(r'^[^.]*\.([^.] )\..*', r'\1', regex=True)
請參閱正則運算式演示。正則運算式匹配所有出現的
^- 字串的開始[^.]*- 零個或多個非點字符\.- 一個點([^.] )- 第 1 組:一個或多個非點字符\.- 一個點.*- 該行的其余部分(盡可能多的除換行符之外的任何零個或多個字符)
并替換為第 1 組值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/420665.html
標籤:
上一篇:將容器盒裝飾應用于其中的按鈕
