我有这段代码:
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']
我想要做的是添加空间而不是所有这些“?。,!:;”所以,如果我必须运行代码,我将得到这个结果:
['i', 'am', 'not', 'not here', 'right', 'now', 'because', 'i', 'am', 'not', 'not good', 'to', 'see', 'that']
所以代码只将'not'添加到下一个单词并在找到空格后中断,但我已经尝试了一切,但没有任何对我有用,如果有人知道如何做到这一点,我将不胜感激。 。 。 提前谢谢。
答案 0 :(得分:1)
我不完全确定你要做什么,但似乎你想把每一个否定都变成双重否定?
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")
答案 1 :(得分:1)
ipsnicerous的优秀代码完全符合您的要求,除了它错过了第一个单词。这可以通过使用is_negative(text [i-1]和更改枚举(text [1:]枚举(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"))