如何在条件 Python 中添加 space

How to add space in conditions Python

我有这个代码:

 def negate_sequence(text):
        negation = False
        delims = "?.,!:;"
        result = []
        words = text.split()
        prev = None
        pprev = None
        for word in words:
            stripped = word.strip(delims).lower()
            negated = "not " + stripped if negation else stripped
            result.append(negated)
            if any(neg in word for neg in ["not", "n't", "no"]):
                negation = not negation

            if any(c in word for c in delims):
                negation = False

        return result

    text = "i am not here right now, because i am not good to see that"
    sa = negate_sequence(text)
    print(sa)

好吧这段代码的作用,基本上是他将 'not' 添加到下一个单词,并且他不会停止添加 'not' 直到他到达其中一个“?.,!:;”它们就像某种中断,例如,如果您 运行 您将获得此代码。

['i', 'am', 'not', 'not here', 'not right', 'not now', 'because', 'i', 'am', 'not', 'not good', 'not to', 'not see', 'not that']

我想要做的是添加 space 而不是所有这些 "?.,!:;"所以如果我必须 运行 代码,我会得到这个结果:

['i', 'am', 'not', 'not here', 'right', 'now', 'because', 'i', 'am', 'not', 'not good', 'to', 'see', 'that']

所以代码只将 'not' 添加到下一个单词,并在找到 space 后中断这样做我将不胜感激。 . . 提前致谢。

我不完全确定你想做什么,但你似乎想把每一个否定都变成双重否定?

def is_negative(word):
    if word in ["not", "no"] or word.endswith("n't"):
        return True
    else:
        return False

def negate_sequence(text):
    text = text.split()
    # remove punctuation
    text = [word.strip("?.,!:;") for word in text]
    # Prepend 'not' to each word if the preceeding word contains a negation.
    text = ['not '+word if is_negative(text[i]) else word for i, word in enumerate(text[1:])]
    return text

print negate_sequence("i am not here right now, because i am not good to see that")

ipsnicerous 的优秀代码完全可以满足您的需求,只是它漏掉了第一个词。这很容易通过使用 is_negative(text[i-1] 并将 enumerate(text[1:] 更改为 enumerate(text[:] 给你:

def is_negative(word):
    if word in ["not", "no"] or word.endswith("n't"):
        return True
    else:
        return False

def negate_sequence(text):
    text = text.split()
    # remove punctuation
    text = [word.strip("?.,!:;") for word in text]
    # Prepend 'not' to each word if the preceeding word contains a negation.
    text = ['not '+word if is_negative(text[i-1]) else word for i, word in enumerate(text[:])]
    return text

if __name__ =="__main__":
    print(negate_sequence("i am not here right now, because i am not good to see that"))