如何将文本元数据实现为 spacy 输出?

How to implement text metadata to spacy output?

我正在尝试构建语料库并使用 spacy 对其进行解析。语料库由 2000 多个单独的文本文件组成,每个文本文件都有特定的文档元数据,例如文件名、性别、国家/地区,数据框中每一行 etc.stored。

到目前为止我所做的是创建一个包含元数据和 text_field 的 EXCEL 文件。 text_field 是存储实际文本的地方。然后我将其导入为 pandas,通过以下代码用 Spacy 解析 text_field;

import spacy
import pandas as pd
nlp = spacy.load('en_core_web_sm')
df = pd.read_excel('C:/Users/Desktop/Data.xlsx')
df['docs'] = list(nlp.pipe(df.text_field))

但是,我想遍历存储在数据框中的所有文档,并使用数据框中提供的元数据提取输出。

比如常见的Spacy输出是这样的;

doc = nlp('this is a test sentence')
for token in doc:
print(token.lemma_, token.text, token.pos_)

lemma / text / pos_
this   this   DET
be     is     AUX
a      a      DET
test   test   NOUN
sentence   sentence   NOUN

预计是这样的;

 file(text/doc metadata) /  lemma / text / pos_
    text1                   this    this   DET
    text1                   be      is     AUX
    text1                   a       a      DET
    text1                   test    test   NOUN
    text1                   sentence sentence NOUN
    text2                   this     this     DET
    text2                   be       is       AUX
    text2                   another  another  DET
    text2                   sentence sentence NOUN
  1. 当我应用 df['docs'] = list(nlp.pipe(df.text_field)) 时,文档列仅包含文本,而不包含文档对象。
  2. 我应该如何继续获得预期的输出?这在带有 Quanteda 包的 R 中是可能的,创建语料库和标记化等,但是有没有办法在 Python 上用 Spacy 做同样的事情?

按照教程 here 我设法创建了一个集成了元数据的语料库。对于那些可能需要的人;

import pandas as pd
import spacy
import textacy
nlp = spacy.load('en_core_web_sm')
df = pd.read_excel('E:/test.xlsx')
native_language = (df
               .sort_values(['Native_language', 
                             'Gender'])
               .groupby('Native_language')['text_field']
               .agg(lambda col: '\n'.join(col)))
docs = list(native_language.apply(lambda x: nlp(x)))
corpus = textacy.corpus.Corpus(nlp, data=docs)

在原来的答案中,提供了 corpus = textacy.corpus.Corpus(nlp, **docs**=docs) 但是,textacy 现在需要数据而不是文档,因此正确的代码是 corpus = textacy.corpus.Corpus(nlp, **data**=docs)