Replacing substrings given a dictionary of strings-to-be-replaced as keys and replacements as values. Python -


i have dictionary strings replaced keys , replacement values. other looking through strings token token, there better/faster way of doing replacement?

i've been doing such:

segmenter = {'foobar':'foo bar', 'withoutspace':'without space', 'barbar': 'bar bar'}  sentence = "this foobar in barbar withoutspace"  in sentence.split():   if in segmenter:     sentence.replace(i, segmenter[i]) 

string immutable in python. so, str.replace returns new string instead of modifying original string. can use str.join() , list comprehension here:

>>> segmenter = {'foobar':'foo bar', 'withoutspace':'without space', 'barbar': 'bar bar'} >>> sentence = "this foobar in barbar withoutspace"  >>> " ".join( [ segmenter.get(word,word) word in sentence.split()] ) 'this foo bar in bar bar without space' 

another problem str.replace it'll replace words "abarbarb"

"abar barb".


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -