把标题缩短到一定长度

2024-05-23 15:58:35 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个标题和一个最大长度,什么是缩短标题的最佳方法?以下是我的想法:

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

Tags: 方法标题lenreturniftitledefshorten
3条回答
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:]

试试看:)

>>> 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之前找不到空格,请显式处理:

^{pr2}$
def shorten_title(title, max_length):
    return title[:max_length + 1]

那怎么样?在

好吧,不用分词,你需要这样:

^{pr2}$

以下是我看到的结果:

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

really long
short
reallylonglon

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

相关问题 更多 >