【问题标题】:How to implement text metadata to spacy output?如何将文本元数据实现为 spacy 输出?
【发布时间】:2021-06-27 20:41:52
【问题描述】:

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

到目前为止,我所做的是创建一个由元数据和 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)) 时,docs 列仅包含文本,而不包含 doc 对象。
  2. 我应该如何继续获得预期的输出?这在带有 Quanteda 包的 R 中是可能的,创建语料库和标记化等,但是有没有办法在 Python 上使用 Spacy 做同样的事情?

【问题讨论】:

    标签: nlp spacy


    【解决方案1】:

    按照教程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)

    【讨论】:

    • 嘿,我不是给你投票的人,但你的问题有点模糊/难以理解,另外没有理由使用截图。
    • @polm23 我明白了,但这毕竟是一个问题。为了清楚起见,我应该编辑帖子。
    猜你喜欢
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 2019-08-13
    • 1970-01-01
    相关资源
    最近更新 更多