Когда у меня есть последовательность таких элементов, я хотел бы настроить небольшую структуру данных, которая указывает, что я ищу, и если я найду его, куда он должен идти.
def strip_currency(s):
"""Function to strip currency and commas from a real number string"""
return s.replace('$', '').replace(',', '')
# mapping of data labels to attribute/key names
label_attr_map = (
('Instagram Usernames', 'usernames'),
('Date', 'date'),
('Address', 'address'),
('Neighborhood', 'market'),
('State', 'city'), # <-- copy-paste bug?
('Asset', 'as_type'),
('Sale Price', 'price', strip_currency),
('Square', 'sf', strip_currency),
('Buyer', 'buyer'),
('Seller', 'seller'),
('Broker', 'broker'),
('Notes', 'notes'),
)
# populate data dict with values from file, as defined in the label_attr_map
data = {}
for line in file:
# find any matching label, or just go on to the next line
match_spec = next((spec for spec in label_attr_map if spec[0] in line), None)
if match_spec is None:
continue
# found a label, now extract the next line, and transform it if necessary
key = match_spec[1]
data[key] = next(file)
if len(match_spec) > 2:
transform_fn = match_spec[2]
data[key] = transform_fn(data[key])
Теперь сопоставление метки и атрибута легче проверить, а каскад «если» - это всего лишь одно выражение next
.
Чтобы записать вывод, просто получите доступ к различным элементам в диктовке data
.