gpt4 book ai didi

python - 使用 spaCy 查找某个单词是否位于两个实体的依赖路径上

转载 作者:行者123 更新时间:2023-12-02 06:20:34 24 4
gpt4 key购买 nike

我正在研究一个 nlp 问题,给定一个包含两个实体的句子,我需要生成 bool 值来指示每个单词是否位于这些实体之间的依赖路径上。

例如:

'A misty < e1 >ridge< /e1 > uprises from the < e2 >surge< /e2 >'

我想迭代每个单词并判断它是否位于 e1 和 e2 之间的依赖路径上

两个重要注意事项:

-如果您尝试帮助我(首先感谢),请不要费心考虑带有 的 xml 标记,我真的很感兴趣如何查找一个单词是否位于任何单词之间的依赖路径上给定两个带有 spaCy 的单词,我自己处理哪些单词

-由于我不是 nlp 专家,我对“依赖路径上”的含义有点困惑,如果不够清楚,我很抱歉(这些是我的导师使用的词)

提前致谢

最佳答案

所以我的解决方案是使用 that post 找到的

有一个专门针对 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']

它实际上做的是首先为句子构建一个无向图,其中单词是节点,单词之间的依赖关系是边,然后找到两个节点之间的最短路径

根据我的需要,我只需检查每个单词是否位于生成的依赖路径(最短路径)上

关于python - 使用 spaCy 查找某个单词是否位于两个实体的依赖路径上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51252914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com