Вопрос : разбить каждую строку на правильную марку, цвет и тип автомобиля.
A = """Item Name
Black Toyota Camry L
Honda Accord Navy
Grey Toyota Corolla
Black Nissan Murano
Silver Toyota Camry LE
"""
B = """Toyota,Nissan,Honda
Camry L,Murano,Accord
Corolla,Rogue,Civic
Avalon,Pathfinder,CR-V
Highlander,Maxima,HR-V
Prius,Altima,
Camry LE,,
"""
- Простейший подход разбиение строк из файла
A
.
из файла B
только первая строка с брендами используется для обнаружения строки, находящейся вне заказа:
Honda Accord Navy
.
import io
def simple_split_title():
# with open(<name of your file B>) as fh:
with io.StringIO(B) as fh:
brands = fh.readline().rstrip().split(',')
# with open(<name of your file A>) as fh:
with io.StringIO(A) as fh:
_ = next(fh)
for line in fh:
title = line.rstrip()
item = title.split(' ')
if item[0] in brands:
_color, _brand, _type, _last = len(item) - 1, 0, 1, len(item) - 1
else:
_color, _brand, _type, _last = 0, 1, 2, len(item)
result = {'title': title,
'brand': item[_brand],
'color': item[_color],
'type': ' '.join(item[_type:_last])}
print(result)
Самый дорогой подход. Для этого требуется l oop
dict
из файла
B
дважды на строку из файла
A
.
Чтобы обнаружить строку не в порядке:
Honda Accord Navy
,
два требуется сравнение строк.
import io, csv
def looping_dict():
# with open(<name of your file B>) as fh:
with io.StringIO(B) as fh:
car_type = [_dict for _dict in csv.DictReader(fh)]
# with open(<name of your file A>) as fh:
with io.StringIO(A) as fh:
_ = next(fh)
for line in fh:
title = line.rstrip()
result = {'title': title, 'brand': '', 'color': '', 'type': ''}
# Get brand
for brand in car_type[0].keys():
if brand in title:
result['brand'] = brand
title = title.replace(brand + ' ', '')
break
# Get type
for _type in car_type:
if title.endswith(_type[brand]) or title.startswith(_type[brand]):
result['type'] = _type[brand]
title = title.replace(_type[brand], '')
break
# Get color
result['color'] = title.strip()
print(result)
Математический подход с использованием
теории множеств .
Список
car_type
зацикливается только
один раз на строку файла
A
.
A extra условие для обнаружения строки с ошибкой:
Honda Accord Navy
,
не обязательно.
Вы получаете совпадение, если
set
из
title items
равны
superset
из
car_type[x].set
.
import io, csv
from collections import namedtuple
def theory_of_sets():
CarType = namedtuple('CarType', 'set brand type')
car_type = []
# with open(<name of your file B>) as fh:
with io.StringIO(B) as fh:
for _dict in csv.DictReader(fh):
for brand, _type in _dict.items():
_set = {brand} | set(_type.split(' '))
car_type.append(CarType._make((_set, brand, _type)))
# with open(<name of your file A>) as fh:
with io.StringIO(A) as fh:
_ = next(fh)
for line in fh:
title = line.rstrip()
_title = title.split(' ')
_items = set(_title)
result = None
for ct in car_type:
if _items.issuperset(ct.set):
result = {'title': title,
'brand': ct.brand,
'color': (_items - ct.set).pop(),
'type': ct.type}
break
print(result)
Вывод : Все три примера выводят один и тот же вывод.
{'title': 'Black Toyota Camry L', 'brand': 'Toyota', 'color': 'Black', 'type': 'Camry L'}
{'title': 'Honda Accord Navy', 'brand': 'Honda', 'color': 'Navy', 'type': 'Accord'}
{'title': 'Grey Toyota Corolla', 'brand': 'Toyota', 'color': 'Grey', 'type': 'Corolla'}
{'title': 'Black Nissan Murano', 'brand': 'Nissan', 'color': 'Black', 'type': 'Murano'}
{'title': 'Silver Toyota Camry LE', 'brand': 'Toyota', 'color': 'Silver', 'type': 'Camry LE'}