【问题标题】:Python: how to assign output from spacy to a list of tuples and then convert to a DataFrame?Python:如何将 spacy 的输出分配给元组列表,然后转换为 DataFrame?
【发布时间】:2021-06-27 08:27:25
【问题描述】:

我正在尝试将 for 循环的打印输出分配给变量 parsed_generics

这是打印输出:

import spacy

nlp = spacy.load("en")
doc = nlp(generics)
for chunk in doc.noun_chunks:
    print(chunk.text, chunk.root.text, chunk.root.dep_, chunk.root.head.text)

Aerobics Aerobics nsubj is
a form form attr is
physical exercise exercise pobj of
rhythmic aerobic exercise exercise dobj combines
stretching and strength training routines routines pobj with
the goal goal pobj with
all elements elements dobj improving
...

要将其分配给变量,这就是我所写的:

nlp = spacy.load("en")
doc = nlp(generics)
for chunk in doc.noun_chunks:
    parsed_generics = (chunk.text, chunk.root.text, chunk.root.dep_, chunk.root.head.text)

但是当我打电话给parsed_generics 时,我得到的是:

('predators', 'predators', 'pobj', 'of')

我猜我期待的是一个元组列表:

[('Aerobics', 'Aerobics', 'nsubj', 'is'), ('a form', 'form', 'attr', 'is'), ('physical exercise', 'exercise', 'pobj', 'of'), ...]

我想我必须在我的 for 循环上方设置一个空列表,遍历 doc 并附加到空列表,但 append 只需要 1 个参数,而我有 4 个 (chunk.text, chunk.root.text, chunk.root.dep_, chunk.root.head.text)

我最终想将其存储在 DataFrame 中。

任何意见或建议将不胜感激。提前谢谢你。

【问题讨论】:

    标签: python dataframe nlp variable-assignment spacy


    【解决方案1】:

    您需要使用附加。您在每次迭代时都会覆盖 parsed_generics,这意味着您看到的是迭代中的最后一行。

    将每次迭代附加到list,然后调用list

    result = []
    
    nlp = spacy.load("en")
    doc = nlp(generics)
    for chunk in doc.noun_chunks:
        result.append((chunk.text, chunk.root.text, chunk.root.dep_, chunk.root.head.text))
    

    【讨论】:

    • 非常感谢;这对我理解非常有帮助。
    猜你喜欢
    • 2017-07-05
    • 2019-06-24
    • 2021-10-24
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多