Python-用字典中的条目替换字符串中的单词

wak*_*ude 2 python dictionary replace key input

我正在尝试制作一个程序,该程序将接受输入,查看这些单词中的任何一个是否是先前定义的字典中的键,然后用它们的条目替换任何找到的单词。难点在于“看看单词是否是关键”。例如,如果我尝试替换该字典中的条目:

dictionary = {"hello": "foo", "world": "bar"}
Run Code Online (Sandbox Code Playgroud)

当给定输入“hello world”时,如何使其打印“foo bar”?

And*_*ker 7

不同的方法

def replace_words(s, words):
    for k, v in words.iteritems():
        s = s.replace(k, v)
    return s

s = 'hello world'
dictionary = {"hello": "foo", "world": "bar"}

print replace_words(s, dictionary)
Run Code Online (Sandbox Code Playgroud)