بتل کد Battle Codeدارد باز می‌شود…

جواب «Text Features to Numbers» چالش 5 از جلسه‌ی 21

سؤال

جدول ویژگیِ متنی دارد: color با مقدارهای red، orange، green. تابع encode(text) بنویس که با دیکشنری {"red": 1, "orange": 0, "green": 2} جدول را به X و y تبدیل کند، طوری که هر سطر X برابر [weight, color_code] باشد. برنامه X را چاپ می‌کند: [[150.0, 1], [170.0, 0], [140.0, 2], [180.0, 0]].

راهنما

w, color, label = line.split(",") و بعد X.append([float(w), codes[color]]).

یک جواب درست

data = '''
weight,color,label
150,red,apple
170,orange,orange
140,green,apple
180,orange,orange
'''.strip()
codes = {"red": 1, "orange": 0, "green": 2}


def encode(text):
    X = []
    y = []
    for line in text.splitlines()[1:]:
        w, color, label = line.split(",")
        X.append([float(w), codes[color]])
        y.append(label)
    return X, y


X, y = encode(data)
print(X)

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن