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

Bag of Words چالش 4 از جلسه‌ی 33، متوسط

تابع bag(sentence, vocab) را کامل کن که لیستی به طول واژه‌نامه برگرداند و در خانه‌ی هر کلمه تعدادش را بنویسد؛ کلمه‌ای که در واژه‌نامه نیست نادیده گرفته شود. خروجی برای دو جمله: [2, 1, 1, 1, 0, 0] و [0, 0, 1, 0, 2, 2].

def tokens(text):
    clean = "".join(ch for ch in text.lower() if ch.isalpha() or ch == " ")
    return clean.split()


vocab = ['a', 'and', 'cat', 'dog', 'sat', 'the']


def bag(sentence, vocab):
    counts = [0] * len(vocab)
    # count each token that is in vocab
    return counts


print(bag("A cat and a dog", vocab))
print(bag("The cat sat on the mat? No, sat!", vocab))

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 33: متن برای کامپیوتر · چالش بعدی: Same Bag, Different Meaning

بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال