gpt4 book ai didi

python - 用顺序名称替换字符串?

转载 作者:太空狗 更新时间:2023-10-30 02:35:48 24 4
gpt4 key购买 nike

我想做的是展示比解释更容易。假设我有一个这样的字符串:

The ^APPLE is a ^FRUIT

使用正则表达式 re.sub(),我想得到这个:

The ^V1 is a ^V2

看看它们是如何递增的。但现在更难了:

The ^X is ^Y but ^X is not ^Z

应该翻译成这样:

The ^V1 is ^V2 but ^V1 is not ^V3

即如果它重复,那么它会保留替换,即 ^X => ^V1 的情况。

我听说替换可以是一个函数,但没弄对。

https://www.hackerrank.com/challenges/re-sub-regex-substitution/problem

最佳答案

IIUC,你不需要re。字符串操作将完成这项工作:

from collections import defaultdict

def sequential(str_):
d = defaultdict(int)
tokens = str_.split()
for i in tokens:
if i.startswith('^') and i not in d:
d[i] = '^V%s' % str(len(d) + 1)
return ' '.join(d.get(i, i) for i in tokens)

输出:

sequential('The ^APPLE is a ^FRUIT')
# 'The ^V1 is a ^V2'

sequential('The ^X is ^Y but ^X is not ^Z')
# 'The ^V1 is ^V2 but ^V1 is not ^V3'

关于python - 用顺序名称替换字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57950394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com