postcode: generate a generic form

This commit is contained in:
Sarah Hoffmann
2022-05-24 17:11:40 +02:00
parent 9cf700e85d
commit 5ba75df507

View File

@@ -37,20 +37,28 @@ class _PostcodeMatcher:
self.output = config.get('output', r'\g<0>') self.output = config.get('output', r'\g<0>')
def normalize(self, postcode): def match(self, postcode):
""" Return the normalized version of the postcode. If the given postcode """ Match the given postcode against the postcode pattern for this
does not correspond to the usage-pattern, return null. matcher. Returns a `re.Match` object if the match was successful
and None otherwise.
""" """
# Upper-case, strip spaces and leading country code. # Upper-case, strip spaces and leading country code.
normalized = self.norm_pattern.fullmatch(postcode.upper()) normalized = self.norm_pattern.fullmatch(postcode.upper())
if normalized: if normalized:
match = self.pattern.fullmatch(normalized.group(1)) return self.pattern.fullmatch(normalized.group(1))
return match.expand(self.output) if match else None
return None return None
def normalize(self, match):
""" Return the default format of the postcode for the given match.
`match` must be a `re.Match` object previously returned by
`match()`
"""
return match.expand(self.output)
class _PostcodeSanitizer: class _PostcodeSanitizer:
def __init__(self, config): def __init__(self, config):
@@ -83,7 +91,8 @@ class _PostcodeSanitizer:
else: else:
obj.address.pop(pos) obj.address.pop(pos)
else: else:
postcode.name = formatted postcode.name = formatted[0]
postcode.set_attr('lookup', formatted[1])
def scan(self, postcode, country): def scan(self, postcode, country):
@@ -94,10 +103,14 @@ class _PostcodeSanitizer:
if country in self.country_without_postcode: if country in self.country_without_postcode:
return None return None
if country in self.country_matcher: matcher = self.country_matcher.get(country)
return self.country_matcher[country].normalize(postcode) if matcher is not None:
match = matcher.match(postcode)
if match is None:
return None
return matcher.normalize(match), ' '.join(match.groups())
return postcode.upper() return postcode.upper(), ''