[英]Replace words in a string, ignoring quotes and matching the whole word
我知道这个问题与此处的其他问题非常相似,但是我无法从任何解决方案中调整一个可行的答案。 道歉!
我希望替换字符串中的单词,忽略引号中的任何内容,并匹配整个单词。
晚上好,我叫汤米,我喜欢足球,“我”最喜欢的运动是足球。
例如,我想替换“ my”,但是我不想替换“ myfootball”中的“ my”或“ my”。
我要替换的单词将从列表中读取。
谢谢,
您可以使用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'
或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.