Python - Replacing words in a string with entries

2019-06-14 16:54发布

问题:

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

回答1:

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)


回答2:

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:

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


回答4:

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)