From f0f681525cb1bdedf7015bf29ed5b80cdaa676db Mon Sep 17 00:00:00 2001 From: Brian Pepple Date: Sun, 22 May 2016 10:33:14 -0400 Subject: Add function to truncate tweet if length will be more than 140 characters --- last_shout.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) (limited to 'last_shout.py') diff --git a/last_shout.py b/last_shout.py index 21a614c..a4b9f82 100755 --- a/last_shout.py +++ b/last_shout.py @@ -100,6 +100,32 @@ class TweetRc(object): self._config.read(os.path.expanduser('~/.tweetrc')) return self._config +def truncate_tweet(s, min_pos=0, max_pos=134, ellipsis=True): + NOT_FOUND = -1 + ERR_MAXMIN = 'Minimum position cannot be greater than maximum position' + + if max_pos < min_pos: + raise ValueError(ERR_MAXMIN) + + if ellipsis: + suffix = '...' + else: + suffix = '' + + length = len(s) + if length <= max_pos: + return s + suffix + else: + try: + # Return it to nearest comma if possible + end = s.rindex(',',min_pos,max_pos) + except ValueError: + # Return string to nearest space + end = s.rfind(' ',min_pos,max_pos) + if end == NOT_FOUND: + end = max_pos + return s[0:end] + suffix + def build_string(list): '''TODO: Add some error checking to modify string if text''' ''' will be more than 140 characters.''' @@ -115,6 +141,7 @@ def build_string(list): elif x == c - 1: txt = txt + " & " x += 1 + txt = truncate_tweet(txt, ellipsis=False) txt = txt + " #music" return txt -- cgit