单线程使用list comprehension
。
[sent.replace(currentWord,newWord) if sent.find(currentWord)>=0 else sent.replace(newWord,currentWord) for sent in sentList]
所以,
IN: sentList = ['i like math', 'i am a cs expert']
IN : currentWord = "math"
IN : newWord = "cs"
OUT : ['i like cs', 'i am a math expert']
这里,if sent.find('math')>=0
会发现,如果字符串conntains 'math'
,如果是这样,与'cs'
替换它,否则它取代'cs'
与'math'
。如果字符串不包含,那么它也会打印原件,因为只有在找到子字符串时,替换才会有效。
编辑:作为@Rawing指出,有在上面的代码中的一些错误。所以这里是处理所有情况的新代码。
我已经使用re.sub
处理更换只有文字,而替换算法是,你将如何交换两个变量,譬如说x
和y
,在这里我们引入一个临时变量t
,以帮助交换: t = x; x = y; y = t
。由于我们必须这样做,所以选择了这种方法。同时多次替换。
from re import sub
for s in sentList:
#replace 'math' with '%math_temp%' in s (here '%math_temp%' is a dummy placeholder that we need to later substitute with 'cs')
temp1 = sub(r'\bmath\b','%math_temp%' , s)
#replace 'cs' with 'math' in temp1
temp2 = sub(r'\bcs\b','math', temp1)
#replace '%math_temp%' with 'cs' in temp2
s = sub('%math_temp%','cs', temp2)
print(s)
所以这次是更大的考验时,我们得到:在这个问题含糊不清的
IN : sentList = ['i like math', 'i am a cs expert', 'math cs', 'mathematics']
IN : currentWord = "math"
IN : newWord = "cs"
OUT : i like cs
i am a math expert
cs math
mathematics
地块。在这里可能有很多场景,就像@Delgan所说的那样。 –