python-3.x - 将 .CSV 数据转换为 NER 的 CoNLL BIO 格式
问题描述
我在 .csv 文件中有一些数据,看起来像这样
sent_num = [0, 1, 2]
text = [['Jack', 'in', 'the', 'box'], ['Jack', 'in', 'the', 'box'], ['Jack', 'in', 'the', 'box']]
tags = [['B-ORG', 'I-ORG', 'I-ORG', 'I-ORG'], ['B-ORG', 'I-ORG', 'I-ORG', 'I-ORG'], ['B-ORG', 'I-ORG', 'I-ORG', 'I-ORG']]
df = pd.DataFrame(zip(sent_num, text, tags), columns=['sent_num', 'text', 'tags'])
df
我想将该数据转换为 CoNLL 格式的文本文件,如下所示,其中每一列(文本和标签)由制表符分隔,每个句子(或文档)的结尾由空行指示。
text tags
Jack B-ORG
in I-ORG
the I-ORG
box I-ORG
Jack B-ORG
in I-ORG
the I-ORG
box I-ORG
Jack B-ORG
in I-ORG
the I-ORG
box I-ORG
我尝试过但未能奏效,它将空行计为有效数据,而不是句子的结尾。
# create a three-column dataset
DF = df.apply(pd.Series.explode)
DF.head()
# insert space between rows in the data frame
# find the indices where changes occur
switch = DF['sent_num'].ne(DF['sent_num'].shift(-1))
# construct a new empty dataframe and shift index by .5
DF1 = pd.DataFrame('', index=switch.index[switch] + .1, columns=DF.columns)
# concatenate old and new dataframes and sort by index, reset index and remove row positions by iloc
DF2 = pd.concat([DF, DF1]).sort_index().reset_index(drop=True).iloc[:-1]
DF2.head()
group by tags
DF2[['text', 'tags']].groupby('tags').count()
我正在寻找一些帮助来修改或改进我拥有的代码。
解决方案
with open("output.txt", "w") as f_out:
print("text\ttags", file=f_out)
for _, line in df.iterrows():
for txt, tag in zip(line["text"], line["tags"]):
print("{}\t{}".format(txt, tag), file=f_out)
print(file=f_out)
创建output.txt
:
text tags
Jack B-ORG
in I-ORG
the I-ORG
box I-ORG
Jack B-ORG
in I-ORG
the I-ORG
box I-ORG
Jack B-ORG
in I-ORG
the I-ORG
box I-ORG
推荐阅读
- websocket - 如何将一系列可观察对象合并为一个。抛出错误“可观察”类型上不存在属性“管道”
[]' - jquery - 执行另一个 ajax 请求后 Ajax 请求不起作用
- ffmpeg - 不支持编解码器 h264_cuvid
- python - 为什么我在提供访问令牌时收到未经授权的代码 (401)?
- angular - Gtk 消息:10:59:42.836:GtkDialog 映射没有临时父级。这是不鼓励的。PID 16131 收到地址的 SIGSEGV:0x10
- python - 多次调用方法时,使用 django rest 序列化程序时缺少一些数据?
- python - 桶时间超过 24 小时时钟,并汇总每个桶的数量
- mysql - 如何在laravel mysql中获取加入和辞职日期内的员工名单,包括空日期
- php - 检查自定义搜索中的帖子类型以获取 Woocommerce 产品属性
- rspec - 当结果是随机的时运行 rspec 测试两次