diff options
author | Brian Pepple <bpepple@fedoraproject.org> | 2016-05-22 10:33:14 -0400 |
---|---|---|
committer | Brian Pepple <bpepple@fedoraproject.org> | 2016-05-22 10:33:14 -0400 |
commit | f0f681525cb1bdedf7015bf29ed5b80cdaa676db (patch) | |
tree | 18260fa47a783449b9b9b8a7788a981c7950e8d2 | |
parent | 10638e02bf7b90440886551a1289dacdd51b5427 (diff) | |
download | scripts-f0f681525cb1bdedf7015bf29ed5b80cdaa676db.tar.gz scripts-f0f681525cb1bdedf7015bf29ed5b80cdaa676db.tar.xz scripts-f0f681525cb1bdedf7015bf29ed5b80cdaa676db.zip |
Add function to truncate tweet if length will be more than 140 characters
-rwxr-xr-x | last_shout.py | 27 |
1 files changed, 27 insertions, 0 deletions
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 |