Python - 用字典中的条目替换字符串中的单词 [英] Python - Replacing words in a string with entries from a dictionary

查看:222
本文介绍了Python - 用字典中的条目替换字符串中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个需要输入的程序,看看这些单词是否是以前定义的字典中的一个键,然后用其输入替换任何找到的单词。硬的是看看是否是键是钥匙。例如,如果我要替换这个字典中的条目:

I am trying to make a program that will take an input, look to see if any of these words are a key in a previously defined dictionary, and then replace any found words with their entries. The hard bit is the "looking to see if words are keys". For example, if I'm trying to replace the entries in this dictionary:

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

如何给它打印foo bar一个输入hello world?

how can I make it print "foo bar" when given an input "hello world"?

推荐答案

这在Python 2.x中有效:

This works in Python 2.x:

dictionary = {"hello": "foo", "world": "bar"}
inp = raw_input(":")
for key in inp.split():
    try:
        print dictionary[key],
    except KeyError:
        continue

但是,如果您使用的是Python 3.x,您将需要:

However, if you are on Python 3.x, you will want this:

dictionary = {"hello": "foo", "world": "bar"}
inp = input(":")
for key in inp.split():
    try:
        print(dictionary[key], end="")
    except KeyError:
        continue

这篇关于Python - 用字典中的条目替换字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆