如何将string
更改为result
?
string = 'John and Mary are good friends'
d = {'John': 'Sam', 'Mary': 'Ann', 'are': 'are not'}
result = 'Sam and Ann are not good friends'
谢谢。
答案 0 :(得分:5)
如果字典中的键只能拆分一个单词,请通过get
和join
的背面进行映射:
a = ' '.join(d.get(x, x) for x in string.split())
print (a)
Sam and Ann are not good friends
如果可能的话,也可以使用多个单词边界,以避免替换子字符串:
import re
string = 'John and Mary are good friends'
d = {'John and': 'Sam with', 'Mary': 'Ann', 'are good': 'are not'}
pat = '|'.join(r"\b{}\b".format(x) for x in d.keys())
a = re.sub(pat, lambda x: d.get(x.group(0)), string)
print (a)
Sam with Ann are not friends
答案 1 :(得分:0)
您可以这样做:
string = 'John and Mary are good friends'
d = {'John': 'Sam', 'Mary': 'Ann', 'are': 'are not'}
result = string
for key, value in d.items():
result = result.replace(key, value)
print(result)
output:
Sam and Ann are not good friends
答案 2 :(得分:0)
1-遍历字符串的每个单词。
2-检查字典键中是否存在单词。
3-如果确实存在,请附加该单词的值以得出结果。如果没有,请在结果后附加单词。
答案 3 :(得分:0)
基本方法:
string = 'John and Mary are good friends'
d = {'John': 'Sam', 'Mary': 'Ann', 'are': 'are not'}
s = string.split()
for i, el in enumerate(s):
if el in d:
s[i] = d[el]
print(' '.join(s))