-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_election_column.py
More file actions
117 lines (93 loc) · 3.55 KB
/
add_election_column.py
File metadata and controls
117 lines (93 loc) · 3.55 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/usr/bin/env python3
"""
Add an election column to issue_relevance_scores.csv based on elections.json.
Usage:
python add_election_column.py \
--scores /path/to/issue_relevance_scores.csv \
--elections /path/to/elections.json \
[--column-name election]
"""
from __future__ import annotations
import argparse
import csv
import json
from pathlib import Path
from typing import Dict, Iterable, Optional
def load_candidacy_to_election_map(elections_path: Path) -> Dict[str, Optional[str]]:
"""Return a mapping of candidacy IDs to their election name."""
with elections_path.open(encoding="utf-8") as elections_file:
data = json.load(elections_file)
mapping: Dict[str, Optional[str]] = {}
if isinstance(data, dict):
elections_iter: Iterable = data.values()
elif isinstance(data, list):
elections_iter = data
else:
raise ValueError("Unexpected elections.json structure; expected dict or list.")
for election in elections_iter:
election_name = election.get("name")
for race in election.get("races", []):
for candidacy in race.get("candidacies", []):
candidacy_id = candidacy.get("id")
if candidacy_id and candidacy_id not in mapping:
mapping[candidacy_id] = election_name
return mapping
def add_election_column(
scores_path: Path,
mapping: Dict[str, Optional[str]],
column_name: str,
output_path: Optional[Path] = None,
) -> None:
"""Add (or replace) the election column in the issue relevance CSV."""
if output_path is None:
output_path = scores_path
with scores_path.open(encoding="utf-8", newline="") as scores_file:
reader = csv.DictReader(scores_file)
if reader.fieldnames is None:
raise ValueError("issue_relevance_scores.csv is missing a header row.")
fieldnames = reader.fieldnames.copy()
if column_name not in fieldnames:
fieldnames.append(column_name)
rows = []
for row in reader:
candidacy_id = row.get("candidate_id")
row[column_name] = mapping.get(candidacy_id)
rows.append(row)
output_path.parent.mkdir(parents=True, exist_ok=True)
with output_path.open("w", encoding="utf-8", newline="") as scores_file:
writer = csv.DictWriter(scores_file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Append an election column to issue_relevance_scores.csv."
)
parser.add_argument(
"--scores",
type=Path,
default=Path("issue_relevance_scores.csv"),
help="Path to issue_relevance_scores.csv (default: ./issue_relevance_scores.csv)",
)
parser.add_argument(
"--elections",
type=Path,
default=Path("issue_alignment") / "elections.json",
help="Path to elections.json (default: ./issue_alignment/elections.json)",
)
parser.add_argument(
"--column-name",
default="election",
help='Name of the column to add/replace (default: "election")',
)
parser.add_argument(
"--output",
type=Path,
help="Path to write the updated CSV (default: overwrite --scores file)",
)
return parser.parse_args()
def main() -> None:
args = parse_args()
mapping = load_candidacy_to_election_map(args.elections)
add_election_column(args.scores, mapping, args.column_name, args.output)
if __name__ == "__main__":
main()