我有一个包含以下键值对的字典:d = {'Alice':'x','Bob':'y','Chloe':'z'}
我想用任何给定字符串中的常量(键)替换小写变量(值)。
例如,如果我的字符串是:
A(x)的B(Y)C(X,Z)
如何替换字符以获得结果字符串:
A(爱丽丝)B(鲍勃)C(爱丽丝,小克)
我应该使用正则表达式吗?
I have a dictionary containing the following key-value pairs: d={'Alice':'x','Bob':'y','Chloe':'z'}
I want to replace the lower case variables(values) by the constants(keys) in any given string.
For example, if my string is:
A(x)B(y)C(x,z)
how do I replace the characters in order to get a resultant string of :
A(Alice)B(Bob)C(Alice,Chloe)
Should I use regular expressions?
最满意答案
具有替换功能的re.sub()解决方案:
import re d = {'Alice':'x','Bob':'y','Chloe':'z'} flipped = dict(zip(d.values(), d.keys())) s = 'A(x)B(y)C(x,z)' result = re.sub(r'\([^()]+\)', lambda m: '({})'.format(','.join(flipped.get(k,'') for k in m.group().strip('()').split(','))), s) print(result)输出:
A(Alice)B(Bob)C(Alice,Chloe)扩大的视野:
import re def repl(m): val = m.group().strip('()') d = {'Alice':'x','Bob':'y','Chloe':'z'} flipped = dict(zip(d.values(), d.keys())) if ',' in val: return '({})'.format(','.join(flipped.get(k,'') for k in val.split(','))) else: return '({})'.format(flipped.get(val,'')) s = 'A(x)B(y)C(x,z)' result = re.sub(r'\([^()]+\)', repl, s) print(result)特定输入案例A(x)B(y)C(Alice,z) 奖励方法:
... s = 'A(x)B(y)C(Alice,z)' result = re.sub(r'\([^()]+\)', lambda m: '({})'.format(','.join(flipped.get(k,'') or k for k in m.group().strip('()').split(','))), s) print(result)re.sub() solution with replacement function:
import re d = {'Alice':'x','Bob':'y','Chloe':'z'} flipped = dict(zip(d.values(), d.keys())) s = 'A(x)B(y)C(x,z)' result = re.sub(r'\([^()]+\)', lambda m: '({})'.format(','.join(flipped.get(k,'') for k in m.group().strip('()').split(','))), s) print(result)The output:
A(Alice)B(Bob)C(Alice,Chloe)Extended version:
import re def repl(m): val = m.group().strip('()') d = {'Alice':'x','Bob':'y','Chloe':'z'} flipped = dict(zip(d.values(), d.keys())) if ',' in val: return '({})'.format(','.join(flipped.get(k,'') for k in val.split(','))) else: return '({})'.format(flipped.get(val,'')) s = 'A(x)B(y)C(x,z)' result = re.sub(r'\([^()]+\)', repl, s) print(result)Bonus approach for particular input case A(x)B(y)C(Alice,z):
... s = 'A(x)B(y)C(Alice,z)' result = re.sub(r'\([^()]+\)', lambda m: '({})'.format(','.join(flipped.get(k,'') or k for k in m.group().strip('()').split(','))), s) print(result)更多推荐
发布评论