python - How to remove a substring from a string based on list of strings -
i have list of strings(colors),
l = ['chocolate brown','brown','chocolate']
i have string:
sentence = "the jeans chocolate brown in color , has brown colored pockets"
i have remove chocolate brown
, brown
string. example. whenever encounter color in string have remove if exists in list of colors. efficient way it?
one approach thought split string trigrams, bigrams , unigrams. joining these n-grams , consistently between n-grams problem.
my original list huge , string short. need efficient solution since have loop on elements of list. possible if check string color , check if color in list. wouldn't efficient solution?
you use re
:
>>> import re >>> l = ['chocolate brown','brown','chocolate'] >>> s = "the jeans chocolate brown in color , has brown colored pockets" >>> >>> re.sub('|'.join(re.escape(r) r in l), '', s) 'the jeans in color , has colored pockets'
Comments
Post a Comment