检查句子中是否存在某些字符串,并使用Python3.6将其替换为另一个字符串

2024-03-28 13:20:18 发布

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

我的程序是检查输入语句是否包含not后跟bad,并将其替换为good。例如,如果句子包含not bad,而在not和{}之间没有任何其他字符串,我可以用good替换它们,如下面的代码所示:

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

结果是:

^{pr2}$

当在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

整个句子都被good代替了。 你能不能建议一下,如果我得到了像下面这样的东西应该怎么做:

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

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

Tags: the代码ininputifis错误not
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)

输出:

^{pr2}$

Regex explanation :

我在这里使用了if else条件正则表达式:

regex中的if else是如何工作的,这是非常简单的if-else regex语法:

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

这意味着“如果命题A为真,那么匹配模式X;否则,匹配模式Y。”

所以在这个正则表达式中:

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

它与“bad”匹配如果字符串中有“not”,则条件为“not”必须出现在字符串中。在

Second Regex :

如果需要,也可以使用此正则表达式:

(not.+)(bad)

在这个组中(2)匹配的是“bad”。在

您的字符串:

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

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

有几种方法可以解决这个问题。一种方法是将句子转换成一个单词列表,在列表中找到“not”和“bad”,删除它们以及它们之间的所有元素,然后插入“good”。在

>>> 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来查找一个匹配“not”的模式,该模式后跟零个或多个单词,后跟“bad”。re.sub函数查找与给定模式匹配的字符串,并将其替换为您提供的字符串:

^{pr2}$

相关问题 更多 >