如何在Python中添加空间

2024-04-19 16:41:27 发布

您现在位置: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’,直到他找到其中一个“?。,!:;“它们就像某种中断,例如,如果您运行此代码,您将得到。你知道吗

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

我想做的是添加空格而不是所有这些“?。,!:;“因此,如果必须运行代码,我将得到以下结果:

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

所以代码只在下一个单词中加上“不”,在找到空格后就中断了,但是我尝试了所有的方法,但是没有任何效果,如果有人知道怎么做,我会很感激的。 提前谢谢。你知道吗


Tags: 代码textinrightforifherenot
2条回答

我不太清楚你想做什么,但似乎你想把每一个否定都变成双重否定?你知道吗

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

ipsniceous的优秀代码完全符合您的要求,只是它漏掉了第一个单词。通过使用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"))

相关问题 更多 >