Skip to content

Commit

Permalink
add two new arguments to ad_from_string
Browse files Browse the repository at this point in the history
slots: to determine the lengths
sep: determining by which character to split the given string
rewrite the algorithm
  • Loading branch information
eliasdabbas committed Jan 17, 2018
1 parent 848d2ea commit 22b1303
Showing 1 changed file with 13 additions and 27 deletions.
40 changes: 13 additions & 27 deletions advertools/ad_from_string.py
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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]

0 comments on commit 22b1303

Please sign in to comment.