Download extract_countries.py from savedata101/repair_data: direct link, hf CLI and curl.
- Browser
- Download file 3.83 kB
-
https://huggingface.co/datasets/savedata101/repair_data/resolve/main/extract_countries.py
- Command line
-
hf download hf://datasets/savedata101/repair_data/extract_countries.py
-
curl -L -o extract_countries.py https://huggingface.co/datasets/savedata101/repair_data/resolve/main/extract_countries.py
3.83 kB
| #!/usr/bin/env python3 | |
| """ | |
| extract_countries.py — Extract unique country names from a CSV. | |
| Assumptions: | |
| - Preferred source is a column named 'country' if present. | |
| - Otherwise, parses a 'location' column formatted roughly as 'city, country'. | |
| - Trims whitespace and canonicalizes common country synonyms (via csv_repair). | |
| Output formats: | |
| - text (default): one country per line to stdout or file | |
| - json: JSON array of countries | |
| - csv: single-column CSV with header 'country' | |
| Usage examples: | |
| python extract_countries.py -i data.csv | |
| python extract_countries.py -i data.csv --format json > countries.json | |
| python extract_countries.py -i data.csv --format csv -o countries.csv | |
| python extract_countries.py -i data.csv --column location --sep ';' --encoding latin-1 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import sys | |
| from typing import List, Optional | |
| import numpy as np | |
| import pandas as pd | |
| try: | |
| # Reuse robust CSV reading and parsing helpers from csv_repair | |
| from csv_repair import try_read_csv, parse_location, canonical_country | |
| except Exception as e: # pragma: no cover | |
| print("This script expects csv_repair.py in the same directory.", file=sys.stderr) | |
| raise | |
| def extract_countries( | |
| df: pd.DataFrame, | |
| column: str = "location", | |
| prefer_country_col: bool = True, | |
| dropna: bool = True, | |
| ) -> List[str]: | |
| if prefer_country_col and "country" in df.columns: | |
| s = df["country"].astype(str).str.strip().replace({"": np.nan}) | |
| elif column in df.columns: | |
| # Parse from location | |
| _, country = parse_location(df[column]) | |
| s = country | |
| else: | |
| raise ValueError(f"Column '{column}' not found and no 'country' column present") | |
| # Canonicalize and clean | |
| s = s.apply(canonical_country) | |
| if dropna: | |
| s = s.dropna() | |
| # Unique sorted list (case-insensitive sort, stable) | |
| uniq = pd.Series(s.unique(), dtype=object).dropna().astype(str) | |
| countries = sorted(uniq.tolist(), key=lambda x: x.casefold()) | |
| return countries | |
| def main(argv: Optional[List[str]] = None) -> int: | |
| p = argparse.ArgumentParser(description="Extract unique country names from a CSV") | |
| p.add_argument("-i", "--input", required=True, help="Path to input CSV") | |
| p.add_argument("--encoding", default=None, help="Optional file encoding (auto if omitted)") | |
| p.add_argument("--sep", default=None, help="CSV delimiter; if omitted, inferred by pandas") | |
| p.add_argument("--column", default="location", help="Column to parse when 'country' not present") | |
| p.add_argument( | |
| "--format", choices=["text", "json", "csv"], default="text", help="Output format" | |
| ) | |
| p.add_argument("-o", "--output", default=None, help="Optional output file; default stdout") | |
| p.add_argument("--keep-nulls", action="store_true", help="Include empty/NA countries in output") | |
| args = p.parse_args(argv) | |
| # Read CSV robustly | |
| df = try_read_csv(args.input, encoding=args.encoding, sep=args.sep) | |
| try: | |
| countries = extract_countries(df, column=args.column, dropna=not args.keep_nulls) | |
| except Exception as e: | |
| print(f"Error: {e}", file=sys.stderr) | |
| return 2 | |
| out = None | |
| if args.format == "text": | |
| out = "\n".join(countries) + ("\n" if countries else "") | |
| elif args.format == "json": | |
| out = json.dumps(countries, ensure_ascii=False, indent=2) | |
| elif args.format == "csv": | |
| # Build a simple CSV; avoid pandas roundtrip to keep deps minimal here | |
| lines = ["country"] + [c.replace("\"", "\"") for c in countries] | |
| out = "\n".join(lines) + "\n" | |
| if args.output: | |
| with open(args.output, "w", encoding="utf-8") as f: | |
| f.write(out) | |
| else: | |
| sys.stdout.write(out) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |