【问题标题】:Is there a way to add each result to a row of the dataframe?有没有办法将每个结果添加到数据框的一行?
【发布时间】:2021-12-10 22:06:10
【问题描述】:

我正在研究一种注释文本的方法,目前正在构建一个函数来将每个文本及其位置添加到数据框上的一行中。

文本:位置:

苹果 PROPN 是辅助 看动词

import spacy
import pandas as pd

df = pd.DataFrame(columns = ['Text', 'pos'])

def annotate(text):
    nlp = spacy.load("en_core_web_sm")
    doc = nlp(text)

    for token in doc:
        print(token.text, token.pos_) 
        df = df.append({'Text' : 'token.text', 'pos' : 'token.pos_'},  ignore_index = True)

annotate('Apple is looking at buying U.K. startup for $1 billion')

【问题讨论】:

  • 不清楚您的问题是什么。这段代码是否如您所愿?
  • 好吧,代码有效,但数据框的创建却无效。我想创建一个包含两列 text 和 pos 的数据框,在每次迭代时,它将在循环中获得 text 中的 'token.text' 和 pos 中的 'token.pos_' 。 @AbbeGijly

标签: python pandas nlp spacy named-entity-recognition


【解决方案1】:

尝试收集数据,然后创建数据框。一般来说,这将比将行附加到现有数据帧更有效:

def annotate(text):
    nlp = spacy.load("en_core_web_sm")
    doc = nlp(text)

    rows = []
    for token in doc:
        print(token.text, token.pos_)
        rows.append([token.text, token.pos])
    df = pd.DataFrame(rows, columns=['Text', 'pos'])
    return df

然后调用它:

df = annotate('Apple is looking at buying U.K. startup for $1 billion')

【讨论】:

  • 非常感谢您的建议! ,它解决了我的问题。 @AbbeGijly
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-30
  • 2021-02-04
  • 2010-11-12
  • 1970-01-01
相关资源
最近更新 更多