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