首页 > 解决方案 > 在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

标签: python

解决方案


将您的 lambda 更改为

lambda row : row[:1]+['NN', 'NN']+row[1:]

并转换为

row = transform_row(row)

推荐阅读