norwegian_parliament / utils /convert_csv_to_json.py
pere's picture
jsonlines
4e81ff1
raw
history blame
No virus
1.74 kB
import csv
import json
import argparse
def convert_csv_to_jsonl(input_csv_path):
# Generate the output file name by replacing .csv with .jsonl
output_jsonl_path = input_csv_path.rsplit('.', 1)[0] + '.jsonl'
# Open the input CSV file and the output JSON lines file
with open(input_csv_path, mode='r', encoding='utf-8') as csv_file, \
open(output_jsonl_path, mode='w', encoding='utf-8') as jsonl_file:
# Create a CSV reader object to read the CSV file
csv_reader = csv.reader(csv_file, delimiter=',')
# Iterate over each row in the CSV file
for row in csv_reader:
# Each row should have exactly four columns: label, text, full_label, date
if len(row) == 4:
label, text, full_label, date = row
# Create a dictionary to represent this record
record = {
'label': label,
'text': text,
'full_label': full_label,
'date': date
}
# Convert the dictionary to a JSON string and write to the JSON lines file
jsonl_file.write(json.dumps(record) + '\n')
else:
print(f"Skipping malformed row: {row}")
def main():
# Create argument parser
parser = argparse.ArgumentParser(description="Convert CSV file to JSONL file.")
# Add argument for input CSV file
parser.add_argument("input_csv_path", type=str, help="Path to the input CSV file.")
# Parse arguments
args = parser.parse_args()
# Convert CSV to JSONL using the provided input path
convert_csv_to_jsonl(args.input_csv_path)
if __name__ == "__main__":
main()