Python:用另一个单词替换第一个出现的单词

2024-06-26 13:09:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有七个水果,你可以用在一个句子里,你可以用一个以上的水果来写,而且可以写很多遍。它们是WatermelonPearPeachOrangeAppleBanana和{}。我想把这句话写回去,同时也要替换第一个出现的水果,不管这个单词被多次显示,还是有多个水果在允许列表中给出,都用布鲁塞尔芽代替,如下所示。在

In: Apple apple apple what is a watermelon have to do to get an apple?

Out: Brussel sprouts apple apple what is a watermelon have to do to get an apple?

In: The apple likes orange

Out: The brussel sprouts likes orange

现在我正在搞乱下面的代码,但这只对一个水果有效,我需要同时检查所有七个,看看哪一个是第一个,并更换它。在

print sentence.replace("apple", "brussel sprouts", 1)

我该怎么做?在


Tags: thetoinanapplegetishave
2条回答

这里有两个独立的问题;第一个问题是^{}'如果水果存在于字符串中,它的位置。第二个是replace第一个被发现的人。既然我不想帮你解决家庭作业问题,我就给你举个小例子,让你从正确的方向开始。在

sentence = "Apple apple apple what is a watermelon have to do to get an apple?".lower() # We lowercase it so that "Apple" == "apple", etc.
index = sentence.find("apple")
print(index)
>>> 0
index = sentence.find("banana") # This is what happens when searching for fruit not in sentence
print(index)
>>> -1

现在您已经了解了find,您应该能够很容易地找到如何组合一系列find和{}操作来获得所需的输出。在

通过re.sub(.*?)首先有助于捕获第一个水果之前的所有字符。模式(?:Watermelon|Pear|Peach|Orange|Apple|Banana|Grapes)与第一个水果名匹配。因此,通过将匹配的字符替换为组索引1中的字符,可以得到所需的输出。在

>>> import re
>>> s = "Apple apple apple what is a watermelon have to do to get an apple?"
>>> re.sub(r'(?i)^(.*?)\b(?:Watermelon|Pear|Peach|Orange|Apple|Banana|Grapes)\b', r'\1brussel sprouts', s)
'brussel sprouts apple apple what is a watermelon have to do to get an apple?'
>>> re.sub(r'(?i)^(.*?)\b(?:Watermelon|Pear|Peach|Orange|Apple|Banana|Grapes)\b', r'\1brussel sprouts', 'The apple likes orange')
'The brussel sprouts likes orange'

(?i)调用了不区分大小写的修饰符,该修饰符强制正则表达式引擎进行不区分大小写的匹配。在

相关问题 更多 >