Same Bag, Different Meaning چالش 5 از جلسهی 33، سخت
نشان بده کیسهی کلمات ترتیب را گم میکند. تابع same_bag(a, b, vocab) بنویس که True برگرداند اگر دو جمله کیسهی یکسان داشته باشند. برنامه سه جفت را امتحان میکند؛ خروجی: True، False، True. (جفت سوم با علامت و حروف بزرگ فرق دارد ولی کیسهاش یکی است.)
def tokens(text):
clean = "".join(ch for ch in text.lower() if ch.isalpha() or ch == " ")
return clean.split()
def bag(sentence, vocab):
counts = [0] * len(vocab)
for word in tokens(sentence):
if word in vocab:
counts[vocab.index(word)] += 1
return counts
vocab = ['bit', 'cat', 'dog', 'likes', 'the']
def same_bag(a, b, vocab):
pass
print(same_bag("the dog bit the cat", "the cat bit the dog", vocab))
print(same_bag("the dog bit the cat", "the dog likes the cat", vocab))
print(same_bag("The Dog likes the cat!", "the cat likes the dog...", vocab))
راهنما و جواب این چالش · برگشت به درس جلسهی 33: متن برای کامپیوتر · چالش بعدی: Nearest Sentence
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال