【问题标题】:Problem with "Span.as_doc()" method in SpacySpacy 中的“Span.as_doc()”方法存在问题
【发布时间】:2020-04-08 20:56:10
【问题描述】:

我正在使用 Spacy 提取与格和直接宾语。 Noun.chunks 已经对其根进行了依赖标记,例如dativedobj,而我要做的是获取Span 并将其保存为Doc 以进行进一步分析。

我有以下代码:

import spacy
nlp = spacy.load("en_core_web_lg")
doc = nlp(open("/-textfile").read())

到目前为止一切顺利,接下来我得到了 Span 对象;

datives = []

for dat in doc.noun_chunks:
    if dat.root.dep_ == "dative" and dat.root.head.pos_ == "VERB":
            dative.append(dat.sent)

现在我有了所有带有noun.chunks 的句子,其中词根是与格,而头部是VERB

但是,我想从datives [] 中获取token 数据

dativesent = datives.as_doc()

但问题是datives [] 已经是一个列表,我无法将其转换为DOC

如何将带有dative-noun.chunks的句子保存为DOC?

【问题讨论】:

    标签: spacy


    【解决方案1】:

    您可以像Doc 一样遍历一个句子(即Span)来访问令牌:

    import spacy
    nlp = spacy.load("en_core_web_sm")
    doc = nlp("She gave the dog a bone. He read a book. They gave her a book.")
    
    dative_sents = []
    for nc in doc.noun_chunks:
        if nc.root.dep_ == "dative" and nc.root.head.pos_ == "VERB":
            dative_sents.append(nc.sent)
    
    for dative_sent in dative_sents:
        print("Sentence with dative:", dative_sent.text)
        for token in dative_sent:
            print(token.text, token.pos_, token.dep_)
        print()
    

    输出:

    Sentence with dative: She gave the dog a bone.
    She PRON nsubj
    gave VERB ROOT
    the DET det
    dog NOUN dative
    a DET det
    bone NOUN dobj
    . PUNCT punct
    
    Sentence with dative: They gave her a book.
    They PRON nsubj
    gave VERB ROOT
    her PRON dative
    a DET det
    book NOUN dobj
    . PUNCT punct
    

    【讨论】:

    • 太棒了。我做了3天的噩梦。所以,真的不需要使用 span.as_doc()。
    猜你喜欢
    • 2017-09-24
    • 1970-01-01
    • 2018-11-23
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2023-04-11
    • 1970-01-01
    相关资源
    最近更新 更多