我试图在不破坏句子空间结构的情况下替换一个单词。假设我有一个句子text = "Hi this is my dog."
。我希望用Simba
来代替狗。根据https://stackoverflow.com/a/57206316/2530674的答复,我做了:
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 .
注意,在句号之前的末尾有一个额外的空格(应该是Hi this is my Simba.
)。有没有办法消除这种行为。很高兴得到一个一般的python字符串处理答案
看来你在找一个常规的替代品?我会的
下面的函数替换任意数量的匹配项(使用spaCy查找),保持与原始文本相同的空格,并适当处理边缘情况(如匹配项位于文本开头时):
text='你好,这是我的狗' 打印(text.replace('dog','simba'))
相关问题 更多 >
编程相关推荐