首页 > 解决方案 > 如何解析特定的句子?

问题描述

考虑这个最小的数据框

import spacy
nlp = spacy.load('en_core_web_sm')
import pandas as pd
import numpy as np    

mydata = pd.DataFrame({'text' : [u'the cat eats the dog. the dog eats the cat']})  

我知道我可以用来apply在我的文本列上运行 spacy:

mydata['parsed'] = mydata.text.apply(lambda x: nlp(x))    

但是,我想做一些更微妙的事情:如何提取主题使用词性标记和的句子dogspacy

输出应该是extracted下面的列:

Out[16]: 
              extracted                                        text
0  the dog eats the cat  the cat eats the dog. the dog eats the cat

谢谢!

标签: pythonpandasspacy

解决方案


这不是一个真正的pandas问题。你有三个问题:

  1. 将每个字符串拆分为多个句子
  2. 确定每个句子的主语
  3. 如果主语是,则返回句子dog

1.我们可以将一个字符串拆分成一个listusingsplit()方法。

my_string = "the dog ate the bread. the cat ate the bread"
sentences = my_string.split('.')

2.根据 Spacy 文档,调用nlp()astring会给我们一个Doc其中包含的内容,其中包含tokens一些properties附加到它们的内容。

property我们感兴趣的是因为它会告诉我们 our和 otherdep_之间的关系,即我们是否是主题。tokentokenstoken

您可以在此处找到属性列表:https ://spacy.io/usage/linguistic-features

doc = nlp(my_string)

for token in doc:
    print(token.dep_)  # if this prints `nsubj` the token is a noun subject!

3.为了检查是否token等于,'dog'我们需要从令牌中获取文本属性:

token.text

如果我们扩大规模:

NLP = spacy.load('en_core_web_sm')

def extract_sentence_based_on_subject(string, subject):

    sentences = string.split('.')

    for sentence in sentences:
        doc = NLP(sentence)
        for token in doc:
            if token.dep_ == 'nsubj':
                if token.text == subject:
                    return sentence


mydata['text'].apply(extract_sentence_based_on_subject, subject='dog')

推荐阅读