| """ |
| Location parser for user survey data. |
| |
| Parses location strings that contain city, state, coordinates, and country |
| information in a single comma-separated string within CSV data. |
| |
| Example formats: |
| - "Baltimore, Maryland, USA" |
| - "Kolding 55.68/12.55,Denmark" |
| - "St Paul Park 48.91/-95.35,USA" |
| - "London, UK" |
| """ |
|
|
| from pathlib import Path |
| from typing import Optional, Dict, Set, List |
| import re |
|
|
| from ..core.base_classes import BaseCleaner |
| from ..core.config import Config |
| from ..core.errata_logger import ErrataLogger |
|
|
|
|
| class LocationParser(BaseCleaner): |
| """ |
| Parses location strings into structured components. |
| |
| Handles: |
| - Coordinate extraction (pattern: NN.NN/NN.NN or NN.NN-NN.NN) |
| - Country identification from list |
| - US state identification (full names and abbreviations) |
| - City extraction from remaining text |
| """ |
|
|
| |
| |
| |
| COORD_PATTERN = re.compile(r'(\d+(?:\.\d+)?[/-]-?\d+(?:\.\d+)?)') |
|
|
| def __init__(self, config: Config, errata_logger: Optional[ErrataLogger] = None): |
| """ |
| Initialize location parser. |
| |
| Args: |
| config: Configuration object |
| errata_logger: Optional errata logger for error tracking |
| """ |
| super().__init__(config, errata_logger) |
|
|
| |
| self.countries = self._load_countries() |
|
|
| |
| self.us_states_full = self._load_us_states_full() |
| self.us_states_abbrev = self._load_us_states_abbrev() |
|
|
| def _load_countries(self) -> Set[str]: |
| """ |
| Load list of country names. |
| |
| Returns: |
| Set of country names (uppercase for case-insensitive matching) |
| """ |
| |
| |
| countries = { |
| 'USA', 'US', 'UNITED STATES', 'UNITED STATES OF AMERICA', |
| 'UK', 'UNITED KINGDOM', 'ENGLAND', 'SCOTLAND', 'WALES', |
| 'CANADA', 'AUSTRALIA', 'NEW ZEALAND', 'IRELAND', |
| 'GERMANY', 'FRANCE', 'SPAIN', 'ITALY', 'NETHERLANDS', |
| 'BELGIUM', 'SWITZERLAND', 'AUSTRIA', 'SWEDEN', 'NORWAY', |
| 'DENMARK', 'FINLAND', 'POLAND', 'CZECH REPUBLIC', |
| 'PORTUGAL', 'GREECE', 'HUNGARY', 'ROMANIA', |
| 'JAPAN', 'CHINA', 'INDIA', 'SOUTH KOREA', 'KOREA', |
| 'BRAZIL', 'ARGENTINA', 'MEXICO', 'CHILE', |
| 'SOUTH AFRICA', 'ISRAEL', 'TURKEY', |
| 'RUSSIA', 'UKRAINE', 'CROATIA', 'SERBIA', |
| 'SINGAPORE', 'MALAYSIA', 'THAILAND', 'PHILIPPINES', |
| 'INDONESIA', 'VIETNAM', 'TAIWAN', |
| 'ICELAND', 'LUXEMBOURG', 'ESTONIA', 'LATVIA', 'LITHUANIA', |
| 'SLOVENIA', 'SLOVAKIA', 'BULGARIA', 'CYPRUS', 'MALTA' |
| } |
|
|
| |
| supplemental_path = Path(self.config.supplemental_dir) / 'countries.txt' |
| if supplemental_path.exists(): |
| try: |
| with open(supplemental_path, 'r', encoding='utf-8') as f: |
| for line in f: |
| line = line.strip().upper() |
| if line and not line.startswith('#'): |
| countries.add(line) |
| except Exception as e: |
| self.log_error( |
| 'country_list_load_failed', |
| f"Failed to load country list: {e}", |
| file_path=str(supplemental_path) |
| ) |
|
|
| return countries |
|
|
| def _load_us_states_full(self) -> Set[str]: |
| """ |
| Load list of US state full names. |
| |
| Returns: |
| Set of state names (uppercase) |
| """ |
| states = { |
| 'ALABAMA', 'ALASKA', 'ARIZONA', 'ARKANSAS', 'CALIFORNIA', |
| 'COLORADO', 'CONNECTICUT', 'DELAWARE', 'FLORIDA', 'GEORGIA', |
| 'HAWAII', 'IDAHO', 'ILLINOIS', 'INDIANA', 'IOWA', |
| 'KANSAS', 'KENTUCKY', 'LOUISIANA', 'MAINE', 'MARYLAND', |
| 'MASSACHUSETTS', 'MICHIGAN', 'MINNESOTA', 'MISSISSIPPI', 'MISSOURI', |
| 'MONTANA', 'NEBRASKA', 'NEVADA', 'NEW HAMPSHIRE', 'NEW JERSEY', |
| 'NEW MEXICO', 'NEW YORK', 'NORTH CAROLINA', 'NORTH DAKOTA', 'OHIO', |
| 'OKLAHOMA', 'OREGON', 'PENNSYLVANIA', 'RHODE ISLAND', 'SOUTH CAROLINA', |
| 'SOUTH DAKOTA', 'TENNESSEE', 'TEXAS', 'UTAH', 'VERMONT', |
| 'VIRGINIA', 'WASHINGTON', 'WEST VIRGINIA', 'WISCONSIN', 'WYOMING', |
| 'DISTRICT OF COLUMBIA', 'DC' |
| } |
|
|
| return states |
|
|
| def _load_us_states_abbrev(self) -> Set[str]: |
| """ |
| Load list of US state abbreviations. |
| |
| Returns: |
| Set of state abbreviations (uppercase) |
| """ |
| abbrevs = { |
| 'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', |
| 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', |
| 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', |
| 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', |
| 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY', 'DC' |
| } |
|
|
| return abbrevs |
|
|
| def parse_location(self, location_str: str) -> Dict[str, Optional[str]]: |
| """ |
| Parse location string into components. |
| |
| Args: |
| location_str: Raw location string |
| |
| Returns: |
| Dictionary with keys: city, state, coordinates, country |
| """ |
| result = { |
| 'city': None, |
| 'state': None, |
| 'coordinates': None, |
| 'country': None |
| } |
|
|
| if not location_str or not isinstance(location_str, str): |
| return result |
|
|
| |
| location_str = location_str.strip() |
| if not location_str: |
| return result |
|
|
| |
| location_upper = location_str.upper() |
|
|
| |
| |
| coord_match = self.COORD_PATTERN.search(location_str) |
| if coord_match: |
| result['coordinates'] = coord_match.group(1) |
| |
| |
| before = location_str[:coord_match.start()].rstrip() |
| after = location_str[coord_match.end():].lstrip() |
|
|
| |
| if after.startswith(','): |
| after = after[1:].lstrip() |
|
|
| |
| if before and after: |
| location_str = before + ', ' + after |
| else: |
| location_str = before + after |
|
|
| location_str = location_str.strip() |
| location_upper = location_str.upper() |
|
|
| |
| parts = [p.strip() for p in location_str.split(',') if p.strip()] |
| parts_upper = [p.upper() for p in parts] |
|
|
| if not parts: |
| return result |
|
|
| |
| country_found = False |
| for i in range(len(parts) - 1, -1, -1): |
| if parts_upper[i] in self.countries: |
| result['country'] = parts[i] |
| parts.pop(i) |
| parts_upper.pop(i) |
| country_found = True |
| break |
|
|
| if not parts: |
| return result |
|
|
| |
| is_usa = result['country'] and result['country'].upper() in {'USA', 'US', 'UNITED STATES', 'UNITED STATES OF AMERICA'} |
|
|
| if is_usa: |
| |
| for i in range(len(parts) - 1, -1, -1): |
| part_clean = parts_upper[i].strip() |
| if part_clean in self.us_states_full or part_clean in self.us_states_abbrev: |
| result['state'] = parts[i] |
| parts.pop(i) |
| parts_upper.pop(i) |
| break |
|
|
| |
| if parts: |
| |
| result['city'] = ' '.join(parts) |
|
|
| return result |
|
|
| def clean( |
| self, |
| data: str, |
| file_path: Optional[str] = None, |
| **kwargs |
| ) -> Dict[str, Optional[str]]: |
| """ |
| Clean and parse location string. |
| |
| Args: |
| data: Location string to parse |
| file_path: Optional file path for error logging |
| **kwargs: Additional parameters |
| |
| Returns: |
| Dictionary with parsed location components |
| """ |
| try: |
| return self.parse_location(data) |
| except Exception as e: |
| self.log_error( |
| 'location_parse_failed', |
| f"Failed to parse location '{data}': {e}", |
| file_path=file_path |
| ) |
| return { |
| 'city': None, |
| 'state': None, |
| 'coordinates': None, |
| 'country': None |
| } |
|
|
| def clean_batch( |
| self, |
| location_strings: List[str] |
| ) -> List[Dict[str, Optional[str]]]: |
| """ |
| Parse a batch of location strings. |
| |
| Args: |
| location_strings: List of location strings to parse |
| |
| Returns: |
| List of parsed location dictionaries |
| """ |
| results = [] |
|
|
| for loc_str in location_strings: |
| results.append(self.parse_location(loc_str)) |
|
|
| return results |
|
|