2019-07-26 18:08:28 +02:00
|
|
|
import pandas as pd
|
2019-07-26 21:11:10 +02:00
|
|
|
import re
|
|
|
|
|
2019-07-28 16:47:28 +02:00
|
|
|
|
2019-07-26 21:11:10 +02:00
|
|
|
def whitespace(field):
|
2019-07-26 18:08:28 +02:00
|
|
|
"""Fix whitespace issues.
|
|
|
|
|
|
|
|
Return string with leading, trailing, and consecutive whitespace trimmed.
|
|
|
|
"""
|
|
|
|
|
2019-07-26 18:31:55 +02:00
|
|
|
# Skip fields with missing values
|
|
|
|
if pd.isna(field):
|
2019-07-26 18:08:28 +02:00
|
|
|
return
|
|
|
|
|
2019-07-26 18:31:55 +02:00
|
|
|
# Initialize an empty list to hold the cleaned values
|
|
|
|
values = list()
|
2019-07-26 18:08:28 +02:00
|
|
|
|
2019-07-26 18:31:55 +02:00
|
|
|
# Try to split multi-value field on "||" separator
|
|
|
|
for value in field.split('||'):
|
|
|
|
# Strip leading and trailing whitespace
|
|
|
|
value = value.strip()
|
2019-07-26 18:08:28 +02:00
|
|
|
|
2019-07-26 18:31:55 +02:00
|
|
|
# Replace excessive whitespace (>2) with one space
|
|
|
|
pattern = re.compile(r'\s{2,}')
|
|
|
|
match = re.findall(pattern, value)
|
2019-07-26 18:08:28 +02:00
|
|
|
|
2019-07-26 18:31:55 +02:00
|
|
|
if len(match) > 0:
|
2019-07-27 08:21:13 +02:00
|
|
|
print(f'Excessive whitespace: {value}')
|
2019-07-26 18:31:55 +02:00
|
|
|
value = re.sub(pattern, ' ', value)
|
2019-07-26 18:08:28 +02:00
|
|
|
|
2019-07-26 18:31:55 +02:00
|
|
|
# Save cleaned value
|
|
|
|
values.append(value)
|
2019-07-26 18:08:28 +02:00
|
|
|
|
2019-07-26 18:31:55 +02:00
|
|
|
# Create a new field consisting of all values joined with "||"
|
|
|
|
new_field = '||'.join(values)
|
2019-07-26 18:08:28 +02:00
|
|
|
|
2019-07-26 18:31:55 +02:00
|
|
|
return new_field
|
2019-07-28 21:53:39 +02:00
|
|
|
|
|
|
|
|
|
|
|
def separators(field):
|
|
|
|
"""Fix for invalid multi-value separators (ie "|")."""
|
|
|
|
|
|
|
|
# Skip fields with missing values
|
|
|
|
if pd.isna(field):
|
|
|
|
return
|
|
|
|
|
|
|
|
# Initialize an empty list to hold the cleaned values
|
|
|
|
values = list()
|
|
|
|
|
|
|
|
# Try to split multi-value field on "||" separator
|
|
|
|
for value in field.split('||'):
|
|
|
|
# After splitting, see if there are any remaining "|" characters
|
|
|
|
pattern = re.compile(r'\|')
|
|
|
|
match = re.findall(pattern, value)
|
|
|
|
|
|
|
|
if len(match) > 0:
|
|
|
|
print(f'Fixing invalid multi-value separator: {value}')
|
|
|
|
|
|
|
|
value = re.sub(pattern, '||', value)
|
|
|
|
|
|
|
|
# Save cleaned value
|
|
|
|
values.append(value)
|
|
|
|
|
|
|
|
# Create a new field consisting of all values joined with "||"
|
|
|
|
new_field = '||'.join(values)
|
|
|
|
|
|
|
|
return new_field
|