0

给定标题和 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
4

3 回答 3

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

如果您只需要打破空间,那应该就足够了。否则,还有其他几篇关于更复杂方法的帖子,例如:截断字符串而不以单词中间结尾

更新以解决来自 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)]
于 2012-04-24T23:38:14.173 回答
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 方法可以做到这一点。

于 2012-04-24T23:28:52.023 回答
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:]

试试看:)

于 2012-04-24T23:39:18.647 回答