簡體   English   中英

替換字符串中的單詞,忽略引號並匹配整個單詞

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM