我的代码......
sentence = "hello world helloworld"
dictionary = {"hello": "1", "world": "2", "helloworld": "3"}
for key in dictionary:
sentence = sentence.replace(key, dictionary[key])
print(sentence)
我想要它做什么...
1 2 3
实际上做了什么......
1 2 12
答案 0 :(得分:2)
试试这个:
sentence = "hello world helloworld"
sentence = sentence.split()
dictionary = {"hello": "1", "world": "2", "helloworld": "3"}
print ' '.join(map(lambda x: dictionary.get(x) or x , sentence))
答案 1 :(得分:1)
如果你的句子可以包含不在你的词典中的单词,应该不加改变地返回,请尝试这种方法:
sentence = "hello world helloworld missing words"
sentence = sentence.split()
dictionary = {"hello": "1", "world": "2", "helloworld": "3"}
for i, word in enumerate(sentence):
sentence[i] = dictionary[word] if word in dictionary else word
print(" ".join(sentence))
答案 2 :(得分:0)
替换的顺序很重要。在你的情况下:
hello
被替换时:“1 world 1world”world
时:“1 2 12”为了避免它按照长度的顺序迭代键。从最长到短。
for key in dictionary.keys().sort( lambda aa,bb: len(aa) - len(bb) ):
sentence = sentence.replace(key, dictionary[key])