我有一个依赖关系图,其中有父节点和子节点。子节点有一个@符号,表示char/number与父节点相同。我知道标题可能很奇怪,让我给你举个例子:
初始参考变量:
ref = '12345.1.1'
需要在中替换的字符串
example1 = '@.1.2'
example2 = '@.@.3'
转换/更换后的结果(这是我需要帮助的(:
# Make some magic, replace @'s with matching parent digits to get this output on string variables above:
example1 = '12345.1.2'
example2 = '12345.1.3'
本质上,我如何将@char(如果存在(替换为其匹配的";"父";字符串数字我想它可能可以使用replace或regex,但如果有任何内置方法可以工作,我很乐意知道。
提前谢谢。
ref = '12345.1.1'
example1 = '@.1.2'
example2 = '@.@.3'
def replace(text, ref='12345.1.1', split='.', placeholder='@'):
ref = ref.split(split)
text = text.split(split)
return split.join(txt1 if txt2 == placeholder else txt2
for txt1, txt2 in zip(ref, text))
print(replace(example1))
print(replace(example2))
print(replace('@.@.@'))
输出
12345.1.2
12345.1.3
12345.1.1
有点麻烦,但这应该可以做到:
import re
class Replacement:
def __init__(self, ref):
self.ref = ref.split(".")
self.counter = 0
def repl(self, match):
if match.group() == "@":
res = self.ref[self.counter]
self.counter += 1
return res
return match.group()
example1 = '@.1.2'
example2 = '@.@.3'
for example in [example1, example2]:
r = Replacement(ref='12345.1.1')
result = re.sub("@", r.repl, example)
print(result)
输出
12345.1.2
12345.1.3
请注意,您需要为输入数据中的每个示例创建一个新的Replacement
对象或重新启动counter
。
简明函数
def replace_char(string: str, palce_holder: str = '@', split: str = '.') -> str:
return split.join((node[0] if node[1] == palce_holder else node[1] for node in zip(ref.split('.'), string.split('.'))))