python - 如何解析特定的句子?
问题描述
考虑这个最小的数据框
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))
但是,我想做一些更微妙的事情:如何提取主题使用词性标记和的句子?dog
spacy
输出应该是extracted
下面的列:
Out[16]:
extracted text
0 the dog eats the cat the cat eats the dog. the dog eats the cat
谢谢!
解决方案
这不是一个真正的pandas
问题。你有三个问题:
- 将每个字符串拆分为多个句子
- 确定每个句子的主语
- 如果主语是,则返回句子
dog
1.我们可以将一个字符串拆分成一个list
usingsplit()
方法。
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_
之间的关系,即我们是否是主题。token
tokens
token
您可以在此处找到属性列表: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')
推荐阅读
- ads - 为 AdSense 自动广告添加标签是否违反政策?
- python - 如何在函数中引用熊猫数据框的索引列
- android - FFmpeg libavcodec/encode.c 无法编译
- coq - 避免 Fixpoint 的隐式参数在证明模式下变得显式
- python-3.x - 使用 Podio API 时出错 - 文件上传操作
- android - Firebase 不会将 OTP 身份验证代码发送到电话号码
- php - 基于位置更新子字符串的 PDO 准备语句
- javascript - 与 Firebase 数据中的键相比,Object.keys 导致顺序不一致/不同
- r - 使用 Alpha Vantage 插件时在 tidyquant (R) 中指定日期
- java - 是否可以显式使用 Java 内部锁?