在python中,如何用字母数字/数字替换特定单词?

在python中,如何用字母数字/数字替换特定单词?,python,regex,pandas,text,replace,Python,Regex,Pandas,Text,Replace,如何将特定单词(即ABC)替换为字母数字/数字,如下图所示 输入数据 what is ABC s123 doing 77 here? what is abc aA574 doing 89 here? what is ABC-X187 doing here? what is aBC^984 doing here? what is Abc647 doing here? what is ABCS123 doing 77 here? what is ABCAA574 doing 89 here? w

如何将特定单词(即ABC)替换为字母数字/数字,如下图所示

输入数据

what is ABC s123 doing 77 here?
what is abc  aA574 doing 89 here?
what is ABC-X187 doing here?
what is aBC^984 doing here?
what is Abc647 doing here?
what is ABCS123 doing 77 here?
what is ABCAA574 doing 89 here?
what is ABCX187 doing here?
what is ABC984 doing here?
what is ABC647 doing here?  
预期输出数据

what is ABC s123 doing 77 here?
what is abc  aA574 doing 89 here?
what is ABC-X187 doing here?
what is aBC^984 doing here?
what is Abc647 doing here?
what is ABCS123 doing 77 here?
what is ABCAA574 doing 89 here?
what is ABCX187 doing here?
what is ABC984 doing here?
what is ABC647 doing here?  
注:任何字母数字均可遵循ABC。这里显示的数字只是示例,不需要硬编码解决方案中的数字

编辑1:刚刚尝试了提议的解决方案。当特殊字符为空格时,它不起作用。因此,请删除重复标记

编辑2:请根据问题处理ABC案件。

您可以使用:

df['col'] = df['col'].str.replace(r'(?<=ABC)\W+(?=\d\d\d)', '')
df['col']=df['col'].str.replace(r'(?您可以使用以下代码:

import re

regex = r"(.*[A-Z]+).*?(\d+.*)"

test_str = """what is ABC 123 doing here?
what is ABC  574 doing here?
what is ABC-187 doing here?
what is ABC^984 doing here?
what is ABC647 doing here?"""

subst = r"\1\2"

result = re.sub(regex, subst, test_str)
print (result)
# what is ABC123 doing here?
# what is ABC574 doing here?
# what is ABC187 doing here?
# what is ABC984 doing here?
# what is ABC647 doing here?

有关regex101的详细信息:

来自


你想删除空格还是标点符号?两者都要。请看问题中的示例。我只想复制这种行为。而不是“什么”在句子的开头,它可以是任何单词。请记住这一点。这个解决方案行吗?我看不到你硬编码ABC,所以请检查一下,然后告诉我。如果有任何问题,我会为你更新我的解决方案!这行得通!但是我只希望替换以ABC开头的单词。你能帮我吗更新您的解决方案以反映相同的情况?您可以在字符集([…])中进行设置。例如:
regex=r“(.[A-C]+).*?(\d++*)”
,仅适用于以-->C开头的单词(表示A、B或C)
0    what is ABC 123 doing here?
1    what is ABC 574 doing here?
2    what is ABC 187 doing here?
3    what is ABC 984 doing here?
4    what is ABC 647 doing here?
dtype: object