简体   繁体   English

替换字符串中的单词,忽略引号并匹配整个单词

[英]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". 例如,我想替换“ my”,但是我不想替换“ myfootball”中的“ my”或“ my”。

The words I want to replace will be read from a list. 我要替换的单词将从列表中读取。

Thanks, 谢谢,

You can use the re module: 您可以使用re模块:

>>> 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: str.replace函数:

>>> 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.'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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