基本上我需要在数据框中取一列,其中包含字符和数字的组合,例如“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 新手,所以我不知道如何做到这一点