python - Applying a dictionary of string replacements to a list of strings -


Say that I have a string and a dictionary specified list of replacements:

Example

  my_replacements = {'1/2': 'half', '1/4': 'quarter', '3/4': 'three quarters'}  

And a list of strings, where each string might contain a key from the above dictionary, such as:

  ['I have my 1/2 bottle', 'me 3/4 profit' ]  

How do I apply a replacement to the list? What would be an insignificant way to do this?

o (n) solution:

  reps = {'1 / 2 ':' half ',' 1/4 ':' quarter ',' 3/4 ':' three quarters') li = ['My 1/2 bottle is only' ',' give me 3/4 of profit '] ([Reps.get (w, w)) [6]: [' I have half a bottle '] ([repsget (w, w)) [] for lamps (lambda s:' '. (S) s.split ()] , 'Give me three quarters of profit'] # For those who do not like 'map', list presentation version: ['' ([For reps.get (w, w)] in sentence sentence.split ()]) in w [9]: ['half bottle', 'give me three quarters of profit]]  

By placing too many replace in the issue loop it makes your algorithm O (NA2). No big deal when you have a replacement principle of length 3, but when it grows up, suddenly you have a very slow algorithm, which is not required.

As mentioned in the observations, this approach depends primarily on being able to token based on empty space - in this way, if you have a white spot in your replacement key ( It is said that you want to change many words), then this approach will not work, however, instead of being able to change terms, the words of the group felt more than the need to change Ing is done, so I disagree with those commentators who believe that this approach is not enough normal.


Comments

Popular posts from this blog

import - Python ImportError: No module named wmi -

Editing Python Class in Shell and SQLAlchemy -

c# - MySQL Parameterized Select Query joining tables issue -