Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
712 views
in Technique[技术] by (71.8m points)

python - How to replace words in a string using a dictionary mapping

I have the following sentence

a = "you don't need a dog"

and a dictionary

dict =  {"don't": "do not" }

But I can't use the dictionary to map words in the sentence using the below code:

''.join(str(dict.get(word, word)) for word in a)

Output:

"you don't need a dog"

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is one way.

a = "you don't need a dog"

d =  {"don't": "do not" }

res = ' '.join([d.get(i, i) for i in a.split()])

# 'you do not need a dog'

Explanation

  • Never name a variable after a class, e.g. use d instead of dict.
  • Use str.split to split by whitespace.
  • There is no need to wrap str around values which are already strings.
  • str.join works marginally better with a list comprehension versus a generator expression.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...