Skip to content

Instantly share code, notes, and snippets.

@ramalho
Created July 24, 2019 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramalho/3147c3e9937b29877bdedde6f3e1f450 to your computer and use it in GitHub Desktop.
Save ramalho/3147c3e9937b29877bdedde6f3e1f450 to your computer and use it in GitHub Desktop.
elide: cut text at or before max_len, keeping complete words if possible
#!/usr/bin/env python3
def elide(text, max_len, ellipsis='…'):
if len(text) <= max_len:
return text
cut = max_len
while cut > 0 and text[cut - 1].isalnum():
cut -= 1
if cut > 0: # found a place to cut
if cut == max_len:
cut -= 1 # discard trailing non-alnum
return text[:cut].strip() + ellipsis
else: # no good place to cut: cut anyway
return text[:max_len - 1] + ellipsis
def main():
import sys
def usage():
print(f'Usage: {sys.argv[0]} one or more words 15')
print('Output: one or more…')
sys.exit()
if len(sys.argv) < 3:
usage()
try:
max_len = int(sys.argv[-1])
except ValueError:
usage()
text = ' '.join(sys.argv[1:-1])
print(elide(text, max_len))
if __name__ == '__main__':
main()
from elide import elide
def test_shorter():
text = 'Simple text'
assert text == elide(text, 12)
def test_exact():
text = 'Simple text'
assert text == elide(text, 11)
def test_elide():
text = 'Simple text'
want = 'Simple…'
assert want == elide(text, 10)
def test_elide_hyphenated():
text = 'Error-prone'
want = 'Error-…'
assert want == elide(text, 10)
def test_elide_after_hyphen():
text = 'Error-prone'
want = 'Error-…'
assert want == elide(text, 7)
def test_elide_at_hyphen():
text = 'Error-prone'
want = 'Error…'
assert want == elide(text, 6)
def test_elide_number():
text = 'War of 1914'
want = 'War of…'
assert want == elide(text, 10)
def test_elide_midword():
text = 'Incomprehensible'
want = 'Incompreh…'
assert want == elide(text, 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment