جواب «Bag of Words» چالش 4 از جلسهی 33
سؤال
تابع bag(sentence, vocab) را کامل کن که لیستی به طول واژهنامه برگرداند و در خانهی هر کلمه تعدادش را بنویسد؛ کلمهای که در واژهنامه نیست نادیده گرفته شود. خروجی برای دو جمله: [2, 1, 1, 1, 0, 0] و [0, 0, 1, 0, 2, 2].
راهنما
for word in tokens(sentence): if word in vocab: counts[vocab.index(word)] += 1.
یک جواب درست
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)
for word in tokens(sentence):
if word in vocab:
counts[vocab.index(word)] += 1
return counts
print(bag("A cat and a dog", vocab))
print(bag("The cat sat on the mat? No, sat!", vocab))
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن