python - 在python的一行csv中插入两个值
问题描述
原始csv:
Identification O
of O
APC2 O
我的代码:
def add_column_in_csv(input_file, output_file, transform_row):
""" Append a column in existing csv using csv.reader / csv.writer classes"""
# Open the input_file in read mode and output_file in write mode
with open(input_file, 'r') as read_obj, open(output_file, 'w', newline='') as write_obj:
# Create a csv.reader object from the input file object
csv_reader = reader(read_obj, delimiter='\t', quotechar='|')
# Create a csv.writer object from the output file object
csv_writer = writer(write_obj, delimiter='\t', quoting=csv.QUOTE_NONE, escapechar='')
# Read each row of the input csv file as list
for row in csv_reader:
# Pass the list / row in the transform function to add column text for this row
transform_row(row)
# Write the updated row / list to the output file
csv_writer.writerow(row)
add_column_in_csv(ncbi_path + '/train_dev.tsv', ncbi_path + '/train_dev.csv', lambda row \
: row.insert(1, 'NN'+'\t'+ 'NN'))
结果:
Identification ['NN', 'NN'] O
of ['NN', 'NN'] O
APC2 ['NN', 'NN'] O
预期的:
Identification NN NN O
of NN NN O
APC2 NN NN O
解决方案
将您的 lambda 更改为
lambda row : row[:1]+['NN', 'NN']+row[1:]
并转换为
row = transform_row(row)
推荐阅读
- java - 是否可以将异常从 java VBean 传递到 Oracle Forms?
- handlebars.js - 车把逃脱单字符
- codenameone - 代号一中有多个 CSS 文件
- delphi - 如何在 Delphi 中为 RDOMail.Find 构造 SQL 查询
- javascript - 为什么 ECMAScript 规范中没有定义一些 javaScript 结构的语法
- sql - 如何在按 desc 排序的前 n 行中查找记录
- reactjs - 如何单击 React 中的按钮并打开表单?
- java - 如何在开发 BLE 应用程序时获取特性的属性
- reactjs - 谷歌登录,通过刷新反应应用程序保持登录
- javascript - 遍历具有多个值的道具的对象会导致 Typescript 错误:Type is not assignable to type never