123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- def smartTruncate(content, begin=0, length=100, addSuffix=False, suffix=' ...', addPrefix=False, prefix='... '):
- '''Truncate a string without cutting a sentence in the middle.
- Syntax: smartTruncate(content, begin=0, length=100, addSuffix=False, suffix=' ...', addPrefix=False, prefix='... ')
- Returns dictionary object with trimmed string 'result' and the index value where it ended 'trimmed_at_index'
- '''
- def finalize(string, wasChanged=False):
- 'This function adds the prefix and suffix and builds the return object'
- if wasChanged:
-
- if begin != 0 and addPrefix is True:
- string = ''.join([prefix, string])
-
- if addSuffix is True:
- string = ''.join([string, suffix])
-
- if end_of_sentence:
- return {'result': string,'trimmed_at_index': end_of_sentence + 1}
- else:
- return {'result': string}
-
- else:
- return {'result': string}
-
- if begin != 0:
- mod_content = content[begin:]
- wasChanged = True
-
- else:
- mod_content = content
-
- if len(mod_content) <= length:
- return finalize(mod_content, wasChanged)
-
- else:
-
- mod_content = content[0:length-1]
-
- mod_content = ''.join([mod_content,' '])
-
- end_of_sentence = mod_content.rfind('. ')+1
-
- mod_content = content[0:end_of_sentence+1]
-
- return finalize(mod_content, wasChanged=True)
|