将标题缩短到一定长度

时间:2012-04-24 23:21:26

标签: python

鉴于标题和max_length,缩短标题的最佳方法是什么?以下是我的想法:

def shorten_title(title, max_length):
    if len(title) > max_length:
        split_title = title.split()
        length = len(title)
        n = 1
        while length > max_length:
            shortened_title = split_title[:length(split_title)-n]
            n+=1
        return shortened_title
    else:
        return title

3 个答案:

答案 0 :(得分:4)

>>> shorten_title = lambda x, y: x[:x.rindex(' ', 0, y)]
>>> shorten_title('Shorten title to a certain length', 20)
'Shorten title to a'

如果你需要打破一个空间就足够了。否则,有更多复杂方法的其他帖子,例如:Truncate a string without ending in the middle of a word

更新以解决来自okm的评论:

要处理边缘情况,比如在max_length之前找不到空格,请明确地解决它们:

def shorten_title2(x, y):
    if len(x) <= y:
        return x
    elif ' ' not in x[:y]:                                          
        return x[:y]
    else:
        return x[:x.rindex(' ', 0, y + 1)]

答案 1 :(得分:1)

def shorten_title(title, max_length):
    return title[:max_length + 1]

那怎么样?

好的,没有分词,你想要这个:

import string

def shorten_title(title, max_length):
    if len(title) > max_length:
        split_title = title.split()
        length = len(title)
        n = 1
        while length > max_length:
            shortened_title = split_title[:-n]
            n = n + 1
            length = len(string.join(shortened_title))
        if shortened_title == []:
            return title[:max_length + 1]
        return string.join(shortened_title)
    else:
        return title

以下是我看到的结果:

print shorten_title("really long long title", 12)
print shorten_title("short", 12)
print shorten_title("reallylonglongtitlenobreaks", 12)

really long
short
reallylonglon

我试图保持代码和逻辑类似于原始海报,但肯定有更多的pythonic方法来做到这一点。

答案 2 :(得分:0)

def shorten_title(title, max_length):
    title_split = split(title)
    out = ""
    if len(title_split[0]) <= max_length:
        out += title_split[0]
    for word in title_split[1:]:
        if len(word)+len(out)+1 <= max_length:
            out += ' '+word
        else:
            break
    return out[1:]

试试:)