简体   繁体   中英

Replace words in a string, ignoring quotes and matching the whole word

I know this question is very similar to other questions on here, however I have not been able to adapt a working answer out of any of the solutions. Apologies!

I am looking to replace words in a string, ignoring anything in quotes, and matching the whole word.

ie good evening my name is Tommy, I like football and "my" favourite sports is myfootball.

I would like to replace 'my', for instance, but I do not want to replace the "my" or 'my' in "myfootball".

The words I want to replace will be read from a list.

Thanks,

You can use the re module:

>>> import re
>>> s = 'good evening my name is Tommy, I like football and "my" favourite sports is myfootball'
>>> re.sub(r"\ my "," your ", s)
'good evening your name is Tommy, I like football and "my" favourite sports is myfootball'

or the str.replace function:

>>> s.replace(' my ',' your ')
'good evening your name is Tommy, I like football and "my" favourite sports is myfootball'
In [84]: re.sub('\s+"|"\s+'," ",s) # sub a " preceded by a space or a "  followed by a space
Ot[84]: 'good evening my name is Tommy"s, I like football and my favourite sports is myfootball.'


In [88]: re.sub(r'"(my)"', r'\1', s)
Out[88]: 'good evening my name is Tommy, I like football and my favourite sports is my football.'

In [89]: re.sub(r'"(\w+)"', r'\1', s)
Out[89]: 'good evening my name is Tommy, I like football and my favourite sports is my   football.'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM