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

标签 python input dictionary replace key

<分区>

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

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

当输入“hello world”时,如何让它打印“foo bar”?

最佳答案

不同的方法

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)

关于Python - 用字典中的条目替换字符串中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20502862/

相关文章:

c - 无法在此 C 程序中找到错误

c# - 填充具有嵌套列表作为值的字典的正确语法是什么?

c++ - 映射和设置插入功能无法解析

python - numpy:如何根据一维数组中的条件从两个二维数组中选取行?

python - 绘制数据并找到最佳拟合线

python - 蝗虫中的“没有命名的模块”

python - 比较三个数字?

python - 文件中字符最多的行?

javascript - 创建按钮 onclick 函数以充当箭头键的作用

python pandas 自定义权重