繁体   English   中英

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

[英]Check if certain Strings are present in a Sentence and Replace them with another String using Python 3.6

我的程序是检查输入句子是否包含not bad ,并用good替换它。 例如,如果句子包含not bad之间没有任何其他字符串notbad ,我能够用替换他们good ,如下面的代码给出:

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

输出是:

>>> The day is good

当在not bad之间存在一些其他单词(或单词)时,就会出现问题。 看看我试过的代码:

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
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正则表达式中的if else如何工作,那么这是非常简单的,如果其他正则表达式语法:

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

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

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

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

如果字符串中的'not'匹配'bad',则字符串中的条件为'not'。

第二个正则表达式:

如果你想要你也可以使用这个正则表达式:

(not.+)(bad)

在这组(2)匹配'坏'。

你的字符串:

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

另一种方法是使用正则表达式来查找匹配“not”后跟零个或多个单词的模式,然后是“bad”。 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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM