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

2024-09-30 06:34:31 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将特定单词(即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?  

注意:任何字母数字都可以跟在ABC后面。这里显示的数字只是示例,不需要硬编码解决方案中的数字。你知道吗

EDIT1:刚刚尝试了提议的解决方案。当特殊字符是空格时,它不起作用。所以请移除重复标签。你知道吗

编辑2:请按问题处理ABC的案件。你知道吗


Tags: 数据hereis字母数字解决方案单词what
3条回答

您可以使用:

df['col'] = df['col'].str.replace(r'(?<=ABC)\W+(?=\d\d\d)', '')

或者

df['col'] = df['col'].map(lambda x: re.sub(r'(?<=ABC)\W+(?=\d\d\d)', '', x))

来自Series.str.replace的文档

s = pd.Series("""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?""".split("\n"))

pattern = r"ABC.*?(\d+)"
s.str.replace(pattern, r"ABC \1")
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

您可以使用以下代码:

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的详细信息:https://regex101.com/r/gGK8fJ/2

相关问题 更多 >

    热门问题