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

时间:2014-08-07 20:48:31

标签: python regex replace

我知道这个问题与此处的其他问题非常相似,但是我无法根据任何解决方案调整工作答案。道歉!

我希望替换字符串中的单词,忽略引号中的任何内容,并匹配整个单词。

即。晚上好,我的名字叫汤米,我喜欢足球,“我最喜欢的运动是我的足球。”

我想取代'my',但我不想替换“myfootball”中的“my”或“my”。

我想要替换的单词将从列表中读取。

谢谢,

2 个答案:

答案 0 :(得分:0)

您可以使用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'

答案 1 :(得分:0)

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