File size: 2,122 Bytes
10757ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import json
import sqlite3
import pandas as pd
import csv


def load_data_from_csv(name, end=58925):
    data = []
    keys = None
    with open(name, "r", encoding="utf-8", errors="ignore") as f:
        csv_data = csv.reader(f)
        for i, line in enumerate(csv_data):
            if i == 0:
                keys = line
                continue
            item = {}
            for key, val in zip(keys, line):
                item[key] = val
            data.append(item)
    return data


def load_data_from_csv_to_db(name, conn, col_names=None):

    # read the dataset from csv file and create a pandas dataframe
    df = pd.read_csv(open(name, "r", encoding="utf-8", errors="ignore"))

    df.columns = [
        'sn', 'candidate_name', 'party_name', 'evm_votes', 'postal_votes', 'total_votes', 'vote_percentage', 'state', 'constituency'
    ]

    df['constituency'] = df['constituency'].str.replace(r'\s*-\s*\d+$', '', regex=True)
    
    # Remove any parenthetical suffixes like (SC) or (ST)
    df['constituency'] = df['constituency'].str.replace(r'\s*\([^)]*\)', '', regex=True)

    # save the dataframe as a database table, name of table is: elections_2019
    result = df.to_sql("elections_2024", conn, if_exists="replace")

    return result


def query_sql(conn, query):
    cursor = conn.cursor()
    cursor.execute(query)
    result = cursor.fetchall()
    field_names = [r[0] for r in cursor.description]
    print(field_names)
    return result


if __name__ == '__main__':
    # create a connection to sql db called elections.db
    conn = sqlite3.connect('../data/elections.db')

    filename = r"../data/eci_data_2024.csv"

    
    data = load_data_from_csv(filename, end=5)

    res = load_data_from_csv_to_db(filename, conn)

    query = "SELECT count(*) FROM elections_2024 WHERE constituency='Amalapuram';"
    results = query_sql(conn, query)
    print(results)

    # keys = data.keys()
    # for i, item in enumerate(data):
    #     print(data[item])
    # jdata = json.loads(data.to_json())
    # print(jdata)