代码之家  ›  专栏  ›  技术社区  ›  twhale

如何用空格标记句子中的动词?蟒蛇

  •  1
  • twhale  · 技术社区  · 7 年前

    我想在动词词尾加上一个“x”来标记句子中的动词,如下所示 verbX

    spacy为python不单独索引的句子元素分配标记。例如,spacy将括号“(”或单词“.”后面的句号看作一个单独的位置,而python则不这样认为。因此,标记的索引不能用来可靠地将x插入到句子中。以下函数通过从标记重建句子来工作。但是,它只允许我在动词的开头插入x。

    有没有办法把x贴在动词的结尾,像这样 韦伯克斯 ?(动词和x之间没有空格。)

    import pandas as pd
    import spacy
    nlp = spacy.load('en')
    
    s = "Dr. John (a fictional chartacter) never shakes hands."
    df = pd.DataFrame({'sentence':[s]})
    k = df['sentence']
    
    def marking(row):
        chunks = []
        for token in nlp(row):
            if token.tag_ == 'VBZ':
                chunks.append('X')
            chunks.append(token.text_with_ws)
        L = "".join(chunks)
        return L
    x = k.apply(marking)
    print(x)   
    

    这就提供了:

    "Dr. John (a fictional chartacter) never Xshakes hands."
    

    我怎么才能拿到这个?

    "Dr. John (a fictional chartacter) never shakesX hands."
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   iacob    7 年前

    问题在于你的操作顺序,为了达到你想要的结果应该是:

    def marking(row):
        chunks = []
        for token in nlp(row):
            chunks.append(token.text_with_ws) #Append word first
            if token.tag_ == 'VBZ':
                chunks.append('X')            #Append 'X' second
        L = "".join(chunks)
        return L
    

    拥有 'X' 直接附加到将任何尾随空格移到结尾的动词上,使用以下逻辑:

    def marking(row):
        chunks = []
        for token in nlp(row):
            if token.tag_ == 'VBZ':
                chunks.append(token.text + 'X' + token.whitespace_)
            else:
                chunks.append(token.text_with_ws)
        L = "".join(chunks)
        return L