我们需要从一个最长为“n”个字符的较大字符串中显示一些“预览文本”。不幸的是,我在 PyPi 上找不到处理这个问题的现有模块。
我希望能做一个适当的解决方案。虽然下面我的快速而肮脏的解决方案有效,但效率并不高——大量的持续比较。有没有人知道如何改进?我尝试了一个正则表达式,但在 20 分钟后放弃了。
我想出的笨拙的解决方案足以满足大多数需求,我只知道这可以更快、更简洁地完成——我很想知道如何做。
sample = "This is a sample string and I would like to break it down by words, without exceeding max_chars."
def clean_cut( text , max_chars ):
rval = []
words = text.split(' ')
for word in words:
len_rval = len(' '.join(rval))
if len_rval + 1 + len(word) > max_chars :
break
rval.append(word)
return ' '.join(rval)
for i in ( 15, 16, 17,30,35):
cutdown = clean_cut( sample , i )
print "%s | %s" % ( i , cutdown )
并且输出是正确的...
15 | This is a
16 | This is a sample
17 | This is a sample
30 | This is a sample string and I
35 | This is a sample string and I would