Reputation: 4261
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
Upvotes: 0
Views: 55
Reputation: 2343
Change your lambda to
lambda row : row[:1]+['NN', 'NN']+row[1:]
and transform to
row = transform_row(row)
Upvotes: 1