Ниже приведено общее решение того, что вы спрашиваете, хотя включение, ожидаемый вывод и пример кода помогли бы убедиться, что этот ответ актуален. Объяснение в комментариях.
import spacy
# Load relevant language/pipeline: here, the built-in small English web-based
# model.
nlp = spacy.load("en_core_web_sm")
# Run text through pipeline to create annotated doc.
sample_text = "Colorless green ideas sleep furiously."
doc = nlp(sample_text)
# Iterate through each token (t) in the doc object, and create a nested list
# of the children of each token. Keep in mind that like many spaCy attributes,
# token.children returns a generator. To access all of its elements at once,
# you will have to convert this generator into an object of type list.
child_list = [list(t.children) for t in doc]
# Now as an exercise, print out each token and check to see if you get the
# children you expected. Normally you would want to iterate on the objects
# themselves -- we only use range() here for purposes of illustration.
for i in range(len(doc)):
print(" token {}: {}".format(i + 1, doc[i]))
print(" children: {}\n".format(child_list[i]))
В соответствии с запросом, приведенным в вопросе, выводится список списков дочерних токенов. Обратите внимание, что хотя ваш терминал будет отображать каждый токен так, как он будет отображаться в тексте, эти токены не просто текстовые;это объекты spaCy token
, каждый из которых загружен лингвистической информацией на основе аннотаций в doc
. Результат будет выглядеть следующим образом.
$ python example.py
token 1: Colorless
children: []
token 2: green
children: []
token 3: ideas
children: [Colorless, green]
token 4: sleep
children: [ideas, furiously, .]
token 5: furiously
children: []
token 6: .
children: []
И это именно то, что мы ожидали: