簡體   English   中英

python替換沒有空格的正則表達式匹配

[英]python replace regex match without spaces

我基本上想“加入”應該清楚地在一起的數字。 我想用它自己替換正則表達式匹配,但沒有任何空格。

我有:

df
               a
'Fraxiparine 9 500 IU (anti-Xa)/1 ml'
'Colobreathe 1 662 500 IU inhalačný prášok v tvrdej kapsule'

我希望有:

df
               a
'Fraxiparine 9500 IU (anti-Xa)/1 ml'
'Colobreathe 1662500 IU inhalačný prášok v tvrdej kapsule'

我正在使用r'\d+\s+\d+\s*\d+'來匹配數字,並且我創建了以下函數來刪除字符串中的空格:

def spaces(x):
    match = re.findall(r'\d+\s+\d+\s*\d+', x)
    return match.replace(" ","")

現在我無法將該函數應用於完整的數據幀,但我也不知道如何用沒有任何空格的字符串替換原始匹配。

嘗試使用以下代碼:

def spaces(s):
    return re.sub('(?<=\d) (?=\d)', '', s)

df['a'] = df['a'].apply(spaces)

正則表達式將匹配:

  • 任何空間
  • 前面有一個數字(?<=\d)
  • 后跟一個數字(?=\d)

然后, pandas.Series.apply函數會將您的函數應用於數據框的所有行。

輸出:

0   Fraxiparine 9500 IU (anti-Xa)/1 ml
1   Colobreathe 1662500 IU inhalačný prášok v tvrd...

我相信您的問題可以通過稍微調整您的函數來解決,以便應用於整個字符串“匹配”,如下所示:

import pandas as pd
import re

df = pd.DataFrame({'a' : ['Fraxiparine 9 500 IU (anti-Xa)/1 ml','Colobreathe 1 662 500 IU inhalačný prášok v tvrdej kapsule']})

# your function
def spaces(x):
    match = re.findall(r'\d+\s+\d+\s*\d+', x)
    replace_with = match[0].replace(" ","")
    return x.replace(match[0], replace_with)

# now apply it on the whole dataframe, row per row
df['a'] = df['a'].apply(lambda x: spaces(x))

利用

df['a'] = df['a'].str.replace(r'(?<=\d)\s+(?=\d)', '', regex=True)

解釋

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  (?<=                     look behind to see if there is:
--------------------------------------------------------------------------------
    \d                       digits (0-9)
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  \s+                      whitespace (\n, \r, \t, \f, and &quot; &quot;) (1 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    \d                       digits (0-9)
--------------------------------------------------------------------------------
  )                        end of look-ahead

如果您的計划是僅刪除\d+\s+\d+\s*\d+中的空格:

df['a'] = df['a'].str.replace(r'\d+\s+\d+\s*\d+', lambda m: re.sub(r'\s+', '', m.group()), regex=True)

str.replace

repl : str 或可調用
替換字符串或可調用對象。 可調用對象傳遞正則表達式匹配對象,並且必須返回要使用的替換字符串。 參見 re.sub()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM