0

original csv:

Identification  O
of      O
APC2    O

my code:

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'))

result:

Identification  ['NN', 'NN']    O
of      ['NN', 'NN']    O
APC2    ['NN', 'NN']    O

expected:

Identification  NN  NN    O
of      NN  NN   O
APC2    NN  NN    O
0

1 Answer 1

1

Change your lambda to

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

and transform to

row = transform_row(row)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.