From 22b13030c1cada75d982faa6b5a2d88ea145047a Mon Sep 17 00:00:00 2001 From: eliasdabbas Date: Wed, 17 Jan 2018 06:45:21 +0400 Subject: [PATCH] add two new arguments to ad_from_string slots: to determine the lengths sep: determining by which character to split the given string rewrite the algorithm --- advertools/ad_from_string.py | 40 ++++++++++++------------------------ 1 file changed, 13 insertions(+), 27 deletions(-) diff --git a/advertools/ad_from_string.py b/advertools/ad_from_string.py index 66efffd0..dd56514e 100644 --- a/advertools/ad_from_string.py +++ b/advertools/ad_from_string.py @@ -1,22 +1,17 @@ import string -def ad_from_string(s, capitalize=True): +def ad_from_string(s, slots=(30, 30, 80, 15, 15), sep=' ', capitalize=False): """Convert string `s` to an ad by splitting it into groups of words. Each group would have a length of at most the allowed length for that slot. If the total length of `s` exceeds the total allowed length, all remaining characters would be grouped in the last element of the returned list. - Main ad slots: - - Headline 1: 30 chars - Headline 2: 30 chars - Description: 80 chars - Path1: 15 chars - Path2: 15 chars Parameters ---------- s : a string of characters, with no restrictions on length. + slots : an iterable of integers for the maximum lengths for each slot + sep : by which character to split `s` capitalize : whether or not to capitalize each word after grouping. Setting it as False would leave the input string as is. @@ -33,27 +28,18 @@ def ad_from_string(s, capitalize=True): ... ['This Is A Longer Ad And Would', 'Take Two Of The First Slots', '', '', '', ''] """ - str_words = [x for x in s.split(' ')] - - h1 = '' - h2 = '' - desc = '' - path1 = '' - path2 = '' - remain = '' - - text_ad = [] + + str_words = s.split(sep=sep) + text_ad = ['' for x in range(len(slots)+1)] counter = 0 - for ad in [[h1, 30],[h2, 30],[desc, 80],[path1, 15],[path2, 15]]: - while (len(ad[0]) <= ad[1]) and (counter <= len(str_words) -1): - if len(ad[0] + str_words[counter]) > ad[1]: + for i, slot in enumerate(slots): + while counter <= len(str_words) - 1: + if len(text_ad[i] + str_words[counter]) >= slot: break - ad[0] += ' ' + str_words[counter] + text_ad[i] += ' ' + str_words[counter] if text_ad[i] else str_words[counter] counter += 1 - text_ad.append(ad[0][1:]) - - remain = ' '.join(str_words[counter:]) - text_ad.append(remain) - return [string.capwords(x) if capitalize else x for x in text_ad] + text_ad[-1] = sep.join(str_words[counter:]) + + return [string.capwords(x) if capitalize else x for x in text_ad] \ No newline at end of file