Python - Replacing words in a string with entries

2019-06-14 16:37发布

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"}

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

4条回答
爷、活的狠高调
2楼-- · 2019-06-14 17:11

The cleanest method is to use dict.get to fallback to the word itself if the word is not in the dictionary:

' '.join([dictionary.get(word,word) for word in 'hello world'.split()])
查看更多
爷的心禁止访问
3楼-- · 2019-06-14 17:17

Assuming a "word" is a continuous sequence of characters, you can split your input on spaces, and then for each word, check if it's in the dictionary or not.

new_str = ""
words = your_input.split(" ")
for i in range(0, len(words)):
  word = words[i]
  if word in dictionary:
    words[i] = dictionary[word]

Now you can do something with your final list of words. For example, join them together separated by spaces

" ".join(words)
查看更多
仙女界的扛把子
4楼-- · 2019-06-14 17:25

Different approach

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)
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-06-14 17:28

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

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
查看更多
登录 后发表回答