You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用DataFrame中的标注列提取多词表达式(MWE)并生成新列

我来帮你搞定这个需求!针对你描述的DataFrame结构,我们可以用Pandas结合简单的字符串处理来提取对应的多词表达式(MWE),下面是具体的实现步骤和代码:

第一步:明确数据结构示例

先假设你的DataFrame长这样(可以对应调整成你实际的数据格式):

import pandas as pd

# 构造示例数据
data = {
    'text': [
        "Barack Obama was president of the United States in 2008.",
        "Apple Inc. was founded in Cupertino, California."
    ],
    'annotation': [
        "MWE_type 0 12; MWE_type 34 47",
        "MWE_type 0 9; MWE_type 30 48"
    ]
}
df = pd.DataFrame(data)

第二步:定义提取MWE的函数

我们写一个自定义函数,用来解析每一行的标注信息,并从文本中截取对应的MWE:

def extract_mwes(text, annotation):
    mwes = []
    # 分割每条标注(假设标注之间用"; "分隔,可根据实际格式调整)
    annotation_entries = annotation.split('; ')
    
    for entry in annotation_entries:
        # 拆分标注的类型、起始索引、结束索引
        parts = entry.strip().split()
        if len(parts) >= 3:  # 确保标注格式正确
            start_idx = int(parts[1])
            end_idx = int(parts[2])
            # Python字符串切片是左闭右开,所以要+1才能包含结束索引的字符
            mwe_text = text[start_idx:end_idx + 1]
            mwes.append(mwe_text)
    
    return mwes

第三步:应用函数生成新列

用apply方法把函数应用到每一行,生成包含MWE列表的新列:

df['extracted_mwes'] = df.apply(lambda row: extract_mwes(row['text'], row['annotation']), axis=1)

查看结果

运行后,你的DataFrame就会新增一列extracted_mwes,内容就是你想要的MWE列表:

print(df[['text', 'extracted_mwes']])

输出示例:

text                extracted_mwes
0  Barack Obama was president of the United State...  [Barack Obama, United States]
1  Apple Inc. was founded in Cupertino, California.    [Apple Inc., Cupertino, California.]

一些额外的注意事项

  • 如果你的标注分隔符不是; (比如用换行、制表符或者单个空格),记得调整split的参数,比如用split('\n')处理换行分隔的标注。
  • 要确保标注里的索引是从0开始的字符索引(和Python字符串的索引规则一致),如果是单词索引或者从1开始计数,需要额外转换。
  • 如果需要保留MWE的类型信息,可以把返回结果改成字典列表,比如:
    mwes.append({"type": parts[0], "text": mwe_text})
    
    这样新列的内容就会是[{"type": "MWE_type", "text": "Barack Obama"}, ...]的格式。

内容的提问来源于stack exchange,提问作者Radix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 02:42:36