I tried to make a generator that generates a C # container class from CSV with Python

It's a hassle to manually create a CSV container class Create a C # container class by automatically parsing CSV types etc. I tried to create a generator. Please note that the CSV format has simple rules.

By the way, Python is just beginning to study There may be something wrong with the code. In that case, it would be very helpful if you could point it out.

Original CSV

I feel like this.

test_csv.csv


id,key1,key2,key3
1,Test 1,1.0,1,
2,Test 2,2.0,2,
3,Test 3,3.0,3,

The top line is the name of the key. This will be the variable name. After that, please enter the contents of csv data from the second line.

Generate result

CSVContainerTestCsv.cs


using System.Collections;
using System.Collections.Generic;

namespace CSVContainer
{
	//Real container data
	public class TestCsv
	{
		public int		 id{ get; private set;}
		public string	 key1{ get; private set;}
		public float	 key2{ get; private set;}
		public int		 key3{ get; private set;}
	}

}

I feel like this. It is enclosed in namespace because it is convenient in various ways.

The class name is a camel case of the CSV file name. The .cs name is "CSVContainer" + class name.

Python code

CSVContainerGenerator.py


# -*- coding: utf-8 -*-

import glob
import os.path

def convert(file):
	count = 0
	culam = ""
	val = ""

	for line in open(file, 'r'):
		if count == 0:
			culam = line
			count += 1
		else:
			val = line
			break

	out_put(file, culam, val)


def out_put(file, culam, val):
	file_name = os.path.basename(file)
	base_name = file_name.replace(".csv","")
	cs_name = "CSVContainer" + to_camel_case(base_name) + ".cs"
	f = create_file(cs_name, base_name)
	create_class(culam, val, f, to_camel_case(base_name))
	# print file_name


def create_file(file, base_name):
	f = open(file, 'w')
	f.write("using System.Collections;\n")
	f.write("using System.Collections.Generic;\n")
	f.write("\n")
	f.write("namespace CSVContainer\n")
	f.write("{\n")
	f.write("\t//Real container data\n")
	f.write("\tpublic class "+to_camel_case(base_name)+"\n")

	return f

def create_class(culam, val, f, base_name):
	f.write("\t{\n")
	culams = culam.split(",")
	vals = val.split(",")
	for i, v in enumerate(culams):
		type_str = ""

		if vals[i].find('.') != -1:
			type_str = "float\t"
		elif vals[i].isdigit():
			type_str = "int\t\t"
		else :
			type_str = "string\t"

		v = v.replace("\n", "")
		v = v.replace("¥n", "")


		f.write("\t\tpublic " + type_str + " " + v + "{ get; private set;}\n")

	f.write("\t}\n")
	f.write("\n")
	f.write("}\n")

def to_camel_case(text):
	text = text.lower()
	text = text.capitalize()

	while '_' in text:
		ix = text.index('_')
		next = text[ix + 1].upper()
		text = text[0:ix] + next + text[ix + 2:]
	return text


for file in glob.glob('CSV/*.csv'):
	print "conv  " , file
	convert(file)

Currently, I go to see the CSV in the CSV directory. The output destination is the same layer as the py code. I hope you can play around with this area. To be honest, it's lazy to make a directory a direct value.

that's all

Recommended Posts

I tried to make a generator that generates a C # container class from CSV with Python
Python: I tried to make a flat / flat_map just right with a generator
[5th] I tried to make a certain authenticator-like tool with python
[2nd] I tried to make a certain authenticator-like tool with python
[Python] A memo that I tried to get started with asyncio
I tried to make a periodical process with Selenium and Python
I tried to make a 2channel post notification application with Python
I tried to make a todo application using bottle with python
[4th] I tried to make a certain authenticator-like tool with python
[1st] I tried to make a certain authenticator-like tool with python
[1 hour challenge] I tried to make a fortune-telling site that is too suitable with Python
I want to make a game with Python
I want to make C ++ code from Python code!
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
I tried to create a class that can easily serialize Json in Python
I tried to touch the CSV file with Python
I tried to draw a route map with Python
[Python] I tried to make a Shiritori AI that enhances vocabulary through battles
I tried to automatically generate a password with Python3
I tried to make a real-time sound source separation mock with Python machine learning
[Mac] I want to make a simple HTTP server that runs CGI with Python
mong --I tried porting the code that randomly generates Docker container names to Python -
I tried to make various "dummy data" with Python faker
I tried to get started with Hy ・ Define a class
I tried to make a stopwatch using tkinter in python
I tried to make GUI tic-tac-toe with Python and Tkinter
I tried to make a function to retrieve data from database column by column using sql with sqlite3 of python [sqlite3, sql, pandas]
[Python] I tried to make an application that calculates salary according to working hours with tkinter
I made a server with Python socket and ssl and tried to access it from a browser
Let's create a program that automatically registers ID/PW from CSV to Bitwarden with Python + Selenium
I also tried to imitate the function monad and State monad with a generator in Python
I want to use a wildcard that I want to shell with Python remove
I tried to make a system that fetches only deleted tweets
Rubyist tried to make a simple API with Python + bottle + MySQL
I tried to make a regular expression of "amount" using Python
[Python] I tried to implement stable sorting, so make a note
I tried to create a list of prime numbers with python
I tried to make a regular expression of "date" using Python
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
Pass a list by reference from Python to C ++ with pybind11
I tried to make a strange quote for Jojo with LSTM
I tried to make an image similarity function with Python + OpenCV
I tried to make a mechanism of exclusive control with Go
[Python] How to make a class iterable
I tried a functional language with Python
I tried to make a Web API
I made a garbled generator that encodes favorite sentences from UTF-8 to Shift-JIS (cp932) in Python
[Python] I tried to make a simple program that works on the command line using argparse.
A story that didn't work when I tried to log in with the Python requests module
I tried to make an original language "PPAP Script" that imaged PPAP (Pen Pineapple Appo Pen) with Python
I tried to communicate with a remote server by Socket communication with Python.
I tried to implement a blockchain that actually works with about 170 lines
I tried to create a program to convert hexadecimal numbers to decimal numbers with python
I came up with a way to make a 3D model from a photo.
I tried to make a calculator with Tkinter so I will write it
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
I tried to develop a Formatter that outputs Python logs in JSON
I tried to discriminate a 6-digit number with a number discrimination application made with python
I tried to send a registration completion email from Gmail with django.
[Outlook] I tried to automatically create a daily report email with Python