1

次のように、長すぎる場合にタイトルを切り捨てる方法を見つけたいと思います。

'this is a title'
'this is a very long title that ...'

特定の文字数を超える場合、mako で文字列を出力し、自動的に「...」で切り捨てる方法はありますか?

ありがとう。

4

2 に答える 2

2

基本的な python ソリューション:

MAXLEN = 15
def title_limit(title, limit):
    if len(title) > limit:
        title = title[:limit-3] + "..."
    return title

blah = "blah blah blah blah blah"
title_limit(blah) # returns 'blah blah bla...'

これはスペースのみをカットします(可能な場合)

def find_rev(str,target,start):
    str = str[::-1]
    index = str.find(target,len(str) - start)
    if index != -1:
        index = len(str) - index
    return index

def title_limit(title, limit):
    if len(title) <= limit: return title
    cut = find_rev(title, ' ', limit - 3 + 1)
    if cut != -1:
        title = title[:cut-1] + "..."
    else:
        title = title[:limit-3] + "..."
    return title

print title_limit('The many Adventures of Bob', 10) # The...
print title_limit('The many Adventures of Bob', 20) # The many...
print title_limit('The many Adventures of Bob', 30) # The many Adventures of Bob
于 2010-10-12T19:17:42.817 に答える
0

webhelpersMAKOテンプレートと密接に関連しています。使用webhelpers.text.truncate-http ://sluggo.scrapping.cc/python/WebHelpers/modules/text.html#webhelpers.text.truncate

于 2013-03-01T10:22:12.300 に答える