【问题标题】:Label custom NER in pandas dataframe在 pandas 数据框中标记自定义 NER
【发布时间】:2021-11-02 11:14:05
【问题描述】:

我有一个包含 3 列的数据框:分别为 'text', 'in', 'tar'type(str, list, list)

                   text                                       in       tar
0  This is an example text that I use in order to  ...       [2]       [6]
1  Discussion: We are examining the possibility of ...       [3]     [6, 7]

intar 表示我要标记到文本中的特定实体,它们返回每个找到的实体术语在文本中的位置。

例如,在in = [3] 的数据框的第二行,我想从text 列中取出第三个单词(即:“are”)并将其标记为@987654328 @。

同样,对于同一行,由于tar = [6,7],我还想从text 列中取出第6 个和第7 个单词(即“可能性”“of”) 并将它们标记为<TAR>possibility</TAR><TAR>of</TAR>

有人可以帮我怎么做吗?

【问题讨论】:

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


    【解决方案1】:

    这不是最优化的实现,但值得得到启发。

    data = {'text': ['This is an example text that I use in order to',
                     'Discussion: We are examining the possibility of the'],
            'in': [[2], [3]],
            'tar': [[6], [6, 7]]}
    df = pd.DataFrame(data)
    cols = list(df.columns)[1:]
    new_text = []
    for idx, row in df.iterrows():
        temp = list(row['text'].split())
        for pos, word in enumerate(temp):
            for col in cols:
                if pos in row[col]:
                    temp[pos] = f'<{col.upper()}>{word}</{col.upper()}>'
        new_text.append(' '.join(temp))
    df['text'] = new_text
    print(df.text.to_list())
    

    输出:

    ['This is <IN>an</IN> example text that <TAR>I</TAR> use in order to', 
     'Discussion: We are <IN>examining</IN> the possibility <TAR>of</TAR> <TAR>the</TAR>']
    

    更新 1

    合并连续出现的相似标签可以如下完成:

    data = {'text': ['This is an example text that I use in order to',
                     'Discussion: We are examining the possibility of the'],
            'in': [[2], [3, 4, 5]],
            'tar': [[6], [6, 7]]}
    df = pd.DataFrame(data)
    cols = list(df.columns)[1:]
    new_text = []
    for idx, row in df.iterrows():
        temp = list(row['text'].split())
        for pos, word in enumerate(temp):
            for col in cols:
                if pos in row[col]:
                    temp[pos] = f'<{col.upper()}>{word}</{col.upper()}>'
        new_text.append(' '.join(temp))
        
    df['text'] = new_text
    for col in cols:
        df['text'] = df['text'].apply(lambda text:text.replace("</"+col.upper()+"> <"+col.upper()+">", " "))
    print(df.text.to_list())
    

    输出:

    ['This is <IN>an</IN> example text that <TAR>I</TAR> use in order to', 'Discussion: We are <IN>examining the possibility</IN> <TAR>of the</TAR>']
    

    【讨论】:

    • 谢谢@meti。我也可以问你,如果不是单独标记'tar'的每个元素,我想将它们标记在一起,例如:可能性,我该怎么做?
    • 这可以使用正则表达式来完成,我会尽快更新解决方案。 @joasa
    猜你喜欢
    • 1970-01-01
    • 2020-06-08
    • 2021-09-30
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    相关资源
    最近更新 更多