我正在处理一个nlp问题,给出了一个包含两个实体的句子,我需要为每个单词生成布尔值,如果它位于这些实体之间的依赖路径上。
例如:
雾< e1 >ridge< /e1 >从< e2 >surge< /e2 >‘
我想对每个单词进行迭代,并判断它是否位于e1和e2之间的依赖路径上。
两个重要注意事项:
-If您试图帮助我(首先谢谢),不要考虑使用< e1 >和< e2 >的xml标记,我非常感兴趣的是如何找到一个单词是否在与spaCy的任意两个给定单词之间的依赖路径上,我自己处理哪个单词。
-As我不是nlp专家,我有点困惑于“依赖路径”的含义,如果不够清楚的话,我很抱歉(这是我的导师使用的)
提前感谢
发布于 2018-07-17 21:57:51
所以我的解决方案是用那个职位找到的
有一个关于spaCy的答案
我的实现,查找给定句子中两个单词之间的依赖路径,
import networkx as nx
import spacy
enter code here
doc = nlp("Ships carrying equipment for US troops are already waiting off the Turkish coast")
def shortest_dependency_path(doc, e1=None, e2=None):
edges = []
for token in doc:
for child in token.children:
edges.append(('{0}'.format(token),
'{0}'.format(child)))
graph = nx.Graph(edges)
try:
shortest_path = nx.shortest_path(graph, source=e1, target=e2)
except nx.NetworkXNoPath:
shortest_path = []
return shortest_path
print(shortest_dependency_path(doc,'Ships','troops'))输出:
['Ships', 'carrying', 'for', 'troops']它实际上所做的是,首先为句子构建一个非定向图,其中单词是节点,单词之间的依赖关系是边,然后找到两个节点之间的最短路径。
为了满足我的需要,我只需检查每个单词是否位于生成的依赖路径(最短路径)上。
发布于 2018-07-10 19:02:29
依赖路径是描述如何在句子中构建子句的一种方法。SpaCy在他们的docs 这里中有一个很好的例子,句子Apple is looking at buying U.K. startup for $1 billion.
请原谅我在这里没有很好的视觉效果,但是让我来看看你的例子:
A misty ridge uprises from the surge.
在spaCy中,我们按照它们的示例获得依赖关系:
import spacy
nlp = spacy.load('en_core_web_lg')
doc = nlp("A misty ridge uprises from the surge.")
for chunk in doc.noun_chunks:
print(chunk.text, chunk.root.text, chunk.root.dep_, chunk.root.head.text)这将得到构成你句子的“从句”。您的输出如下所示:
Text | root.text| root.dep_ | root.head.text
A misty ridge uprises uprises ROOT uprises
the surge surge pobj fromchunk.text是构成依赖子句的文本(注意,根据句子结构,可能存在重叠)。root.text给出依赖树的根(或头)。树的head是一个spaCy token对象,具有可以迭代的子对象,以检查依赖树上是否有另一个令牌。
def find_dependencies(doc, word_to_check=None, dep_choice=None):
"""
word_to_check is the word you'd like to see on the dependency tree
example, word_to_check="misty"
dep_choice is the text of the item you'd like the dependency check
to be against. Example, dep_choice='ridge'
"""
tokens, texts = [], []
for tok in doc:
tokens.append(tok)
texts.append(tok.text)
# grabs the index/indices of the token that you are interested in
indices = [i for i,text in enumerate(texts) if text==dep_choice]
words_in_path = []
for i in indices:
reference = tokens[i]
child_elements = [t.text for t in reference.get_children()]
if word_to_check in child_elements:
words_in_path.append((word_to_check, reference))
return words_in_path代码并不是最漂亮的,但这是一种可以获得包含要检查的单词和关联的父标记的元组列表的方法。希望这会有帮助
编辑:
为了更好地适应您的用例(并极大地简化我最初的答案是什么样子):
# This will give you 'word':<spaCy doc object> key value lookup capability
tokens_lookup = {tok.text:tok for tok in doc}
if "misty" in tokens_lookup.get("ridge").children:
# Extra logic herehttps://stackoverflow.com/questions/51252914
复制相似问题