Skip to main content
 首页 » 编程设计

python之用字符串和附加到它的数字的长度替换字符串中的数字

2025年02月15日18freeliver54

基本上,我需要在数据框中提取一个包含字符和数字组合的列,例如“XYZABC/123441 s sdx”和类似类型

我需要删除所有标点符号、单字母单词、将双空格替换为单空格、修剪字符串并将数字替换为“NUMB#”,其中“#”代表数字的长度。所以这里的 '123441' 将被替换为 "NUMB6"等等。

我当前的代码是:

for x in df["colname"]: 
    x = re.sub(r"[^\w\s]", " ", str(x))      #Removes all punctuations 
    x = re.sub(r"\d+", "NUMB", str(x))       #Replaces digits with 'NUMB' 
    x = re.sub(r"\b[a-zA-Z]\b", "", str(x))  #Removes all single characters 
    x = re.sub(r"\s+", " ", str(x))          #Removes double spaces with single space 
    x = x.strip().upper()                    #Trims the string 

现在我确实在网站上看到一个关于如何用长度替换子字符串的问题:

re.sub(r'\b([A-Z][a-z]*)\b', lambda m: str(len(m.group(1))), s) 

我在这里需要做的就是将“([A-Z][a-z]*)”替换为“\d”。但是,我不知道如何将两者附加在一起,'.append' 函数不起作用。这可能是一件基本的事情,但我是 Python 的新手,所以我不确定该怎么做

请您参考如下方法:

你可以像这样使用apply

def repl(x): 
    return re.sub(r'\d+', lambda m: "NUMB{}".format(len(m.group())), x) 
 
 df['colname'] = df['colname'].apply(repl) 

或者使用与代码中相同的逻辑,将 x = re.sub(r"\d+", "NUMB", str(x)) 替换为

x = re.sub(r'\d+', lambda m: "NUMB{}".format(len(m.group())), x) 

re.sub(r'\d+', lambda m: "NUMB{}".format(len(m.group())), x) 会找到任何不重叠的数字 block ,并将用 NUMB 和数字 block 的长度替换它们。