2017-10-14 31 views
1

我的程序是检查输入句子是否包含not,然后是bad,并用good替换它。例如,如果句子包含not bad没有任何其他字符串中notbad之间,我能够与good来替换它们,如下面的代码给出:检查句子中是否存在某些字符串并用Python替换为另一个字符串3.6

s = 'The day is not bad' 
s = s.replace('not bad', 'good') 
print(s) 

输出功率为:

>>> The day is good 

notbad之间存在一些其他单词(或单词)时,就会出现问题。 看一看代码我想:

l = ['not', 'bad'] 
s = 'The day is not so bad' 
if l in s: 
    s = s.replace(l,'good') 

它扔像以下的错误而预期输出必须是The day is good

Traceback (most recent call last): 

    File "<ipython-input-69-0eb430659d1e>", line 3, in <module> 
    if l in s: 

TypeError: 'in <string>' requires string as left operand, not list 

我想这样的事情太:

list_ = ['not', 'bad'] 
if any(word in 'The day is not at all bad' for word in list_): 
s = s.replace(s,'good') 

但我得到的上述代码的错误输出是:

>>> s 
>>> good 

IOW,整句改为good。 您能否提供应做什么,如果我要得到的东西像下面这样:

>>> s = 'The day is not at all bad' #input 

>>> print(output) 
>>> 'The day is good' # the desired output 
+1

最后我得到了你想要的东西,我已经更新了我的回答,请检查。 –

回答

1

有一对夫妇,你可以接近这个方式。一种方法是将句子转换为单词列表,在列表中找到“不”和“坏”,将它们和所有元素删除,然后插入“好”。

>>> s = 'the day is not at all bad' 
>>> start, stop = 'not', 'bad' 
>>> words = s.split() 
>>> words 
['the', 'day', 'is', 'not', 'at', 'all', 'bad'] 
>>> words.index(start) 
3 
>>> words.index(stop) 
6 
>>> del words[3:7] # add 1 to stop index to delete "bad" 
>>> words 
['the', 'day', 'is'] 
>>> words.insert(3, 'good') 
>>> words 
['the', 'day', 'is', 'good'] 
>>> output = ' '.join(words) 
>>> print(output) 
the day is good 

另一种方法是使用regular expressions找到相匹配的模式“而不是”后跟零个或多个字,其次是“坏”。该re.sub函数查找匹配给定模式的字符串,并与您提供的字符串替换它们:

>>> import re 
>>> pattern = r'not\w+bad' 
>>> re.search(pattern, s) 
>>> pattern = r'not(\s+\w+)* bad' # pattern matches "not <words> bad" 
>>> re.sub(pattern, 'good', s) 
'the day is good' 
2
import re 
s = 'The day is at not all bad' 
pattern=r'(not)(?(1).+(bad))' 

match=re.search(pattern,s) 

new_string=re.sub(pattern,"good",s) 

print(new_string) 

输出:

The day is at good 

正则表达式的解释:

我用if else此条件的正则表达式:

如何if else在正则表达式的作品,以及这是如果是简单的正则表达式的其他语法:

(condition1)(?(1)(do something else)) 
(?(A)X|Y) 

这意味着“如果一个命题为真,则匹配模式X;否则,匹配模式Y.”

所以在这个表达式:

(not)(?(1).+(bad)) 

它匹配‘坏’如果‘不是’字符串中,条件是‘不’必须在字符串中出现。

二正则表达式:

如果你愿意,你也可以使用这个表达式:

(not.+)(bad) 

在这个团体(2)符合 '坏'。

您的字符串:

>>> s = 'The day is not at all bad' #input 

>>> print(output) 
>>> 'The day is good' # output 
+0

不知道这个地址在单词“not”之后寻找单词“bad”*的地址...另外,对于你的例句,为什么你要在替换之前检查字符串是否存在?只是尝试并更换它,如果它不存在,什么都不会发生......两次扫描's'没有多少意义... –

相关问题