如何保留依赖关系的顺序?

问题描述:

我有以下代码打开目录中的文件,对它们运行spaCy NLP,输出依赖项将信息解析到新目录中的文件中。如何保留依赖关系的顺序?

import spacy, os 

nlp = spacy.load('en') 

path1 = 'C:/Path/to/my/input' 
path2 = '../output' 
for file in os.listdir(path1): 
    with open(file, encoding='utf-8') as text: 
     txt = text.read() 
     doc = nlp(txt) 
     for sent in doc.sents: 
      f = open(path2 + '/' + file, 'a+') 
      for token in sent: 
       f.write(file + '\t' + str(token.dep_) + '\t' + str(token.head) + '\t' + str(token.right_edge) + '\n') 
    f.close() 

问题在于,这不会保留输出文件中依赖关系的顺序。我似乎无法在API文档中找到对字符位置的任何引用。

字符索引为token.idx。词索引在token.i。我知道这不是特别直观。

令牌也被位置比较,所以你可以这样做:

for child in sent: 
    word1, word2 = sorted((child, child.head)) 

这将让你的每个依赖性弧线,排列文档顺序。尽管如此,我不确定你想要做什么,但我不确定这是否完全符合你的要求。

+0

谢谢syllogism_!这很好。我结束了以下内容:'为孩子送: \t \t \t \t头= child.head \t \t \t \t head_pos = child.head.tag_ \t \t \t \t常量=小孩 \t \t \t \t const_pos = child.tag_ \t \t \t \t f.write(file +'\ t'+ str(child.idx)+'\ t'+ str(child.dep_)+'\ t'+ str(head)+'\ t'+ str(head_pos)+'\ t'+ str(const)+'\ t'+ str(const_pos) +'\ n')' – Shane