smartTruncate_python_2.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. def finalize(string, wasChanged=False):
  2. 'This function adds the prefix and suffix and builds the return object'
  3. if wasChanged:
  4. #if a begin value was given, and prefix was requested, add prefix
  5. if begin != 0 and addPrefix is True:
  6. string = ''.join([prefix, string])
  7. #if suffix was requested, add suffix
  8. if addSuffix is True:
  9. string = ''.join([string, suffix])
  10. #if it was trimmed, include that in the result set
  11. if end_of_sentence:
  12. return {'result': string,'trimmed_at_index': end_of_sentence + 1}
  13. else:
  14. return {'result': string}
  15. #if it wasn't changed then just return the string
  16. else:
  17. return {'result': string}
  18. #cut beginning value from content
  19. if begin != 0:
  20. mod_content = content[begin:]
  21. wasChanged = True
  22. #make sure variable mod_content is created
  23. else:
  24. mod_content = content
  25. #if content.length is less than desired length then return the content unmodified
  26. if len(mod_content) <= length:
  27. return finalize(mod_content, wasChanged)
  28. #else if the content.length is longer than desired length then:
  29. else:
  30. #first, trim character count to desired length
  31. mod_content = content[0:length-1]
  32. #add a trailing space in case the final character is a period and we already ended on a perfect sentence boundary
  33. mod_content = ''.join([mod_content,' '])
  34. #second, find the last-most period or sentence termination including the period
  35. end_of_sentence = mod_content.rfind('. ')+1
  36. #third, trim to the last full sentence
  37. mod_content = content[0:end_of_sentence+1]
  38. #final, return the modified content
  39. return finalize(mod_content, wasChanged=True)