Generate code to clean addresses
- User
Generate code to clean addresses
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Generate code to clean addresses
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Cleaning addresses is a common task in data preprocessing. The goal is to standardize address formats so that they can be reliably used for tasks like geocoding, matching, or database normalization.
Here's a Python function using basic string manipulation and regular expressions (re) to clean and standardize addresses:
import re
def clean_address(address):
"""
Cleans and standardizes an address string.
Parameters:
address (str): Raw address string
Returns:
str: Cleaned and standardized address
"""
if not isinstance(address, str):
address = str(address)
# Convert to lowercase first for uniformity
address = address.lower().strip()
# Replace multiple spaces and line breaks with a single space
address = re.sub(r'\s+', ' ', address).strip()
# Abbreviation replacements
abbr_map = {
'st': 'Street',
'ave': 'Avenue',
'blvd': 'Boulevard',
'dr': 'Drive',
'pl': 'Place',
'ln': 'Lane',
'rd': 'Road',
'ter': 'Terrace',
'cir': 'Circle',
'ct': 'Court',
'trl': 'Trail',
'hwy': 'Highway',
'pkwy': 'Parkway',
'ext': 'Extension',
'n': 'North',
's': 'South',
'e': 'East',
'w': 'West',
'ne': 'Northeast',
'nw': 'Northwest',
'se': 'Southeast',
'sw': 'Southwest'
}
# Split into parts to replace abbreviations
parts = re.split(r'(\d+|\b\w+\b)', address)
cleaned_parts = []
for part in parts:
if not part:
continue
# If it's a word and in the map, replace it
elif part in abbr_map:
cleaned_parts.append(abbr_map[part])
else:
cleaned_parts.append(part)
address = ''.join(cleaned_parts)
# Capitalize words
address = address.title()
return address.strip()
raw_address = " 123 main st, Apt 5B, new york, NY 10001 "
cleaned = clean_address(raw_address)
print(cleaned)
# Output: 123 Main Street, Apt 5B, New York, Ny 10001
You can integrate this with external tools like:
Let me know if you want a version tailored for:
usaddress)Would you like an example using usaddress?