I am trying to replace a word without destroying the space structure in the sentence. Suppose I have the sentence text = "Hi this is my dog."
. And I wish to replace dog with Simba
. Following the answer from https://stackoverflow.com/a/57206316/2530674 I did:
import spacy
nlp = spacy.load("en_core_web_lg")
from spacy.tokens import Doc
doc1 = nlp("Hi this is my dog.")
new_words = [token.text if token.text!="dog" else "Simba" for token in doc1]
Doc(doc1.vocab, words=new_words)
# Hi this is my Simba .
Notice how there was an extra space at the end before the full stop (it ought to be Hi this is my Simba.
). Is there a way to remove this behaviour. Happy for a general python string processing answer too.