我正在寻找一种方法来截断Python中的字符串,该字符串不会切断单词中间的字符串.
例如:
Original: "This is really awesome." "Dumb" truncate: "This is real..." "Smart" truncate: "This is really..."
我正在寻找一种从上面完成"智能"截断的方法.
Ada*_*dam 61
我实际上是在最近的一个项目中为此写了一个解决方案.我把它的大部分压缩到了一点点.
def smart_truncate(content, length=100, suffix='...'):
if len(content) <= length:
return content
else:
return ' '.join(content[:length+1].split(' ')[0:-1]) + suffix
Run Code Online (Sandbox Code Playgroud)
会发生什么是if语句检查您的内容是否已经小于截止点.如果不是,它会截断到所需的长度,在空格上分割,删除最后一个元素(这样你就不会切断一个单词),然后将它连接在一起(同时加上'...') .
bob*_*nce 45
这是Adam解决方案中最后一行的稍微好一点的版本:
return content[:length].rsplit(' ', 1)[0]+suffix
Run Code Online (Sandbox Code Playgroud)
(这稍微更有效,并且在字符串前面没有空格的情况下返回更合理的结果.)
Bri*_*ian 11
有一些细微之处可能会或可能不是你的问题,例如标签的处理(例如,如果你将它们显示为8个空格,但在内部将它们视为1个字符),处理各种风格的破坏和非打破空格,或允许打破连字符等.如果需要这样做,您可能需要查看textwrap模块.例如:
def truncate(text, max_size):
if len(text) <= max_size:
return text
return textwrap.wrap(text, max_size-3)[0] + "..."
Run Code Online (Sandbox Code Playgroud)
大于max_size的单词的默认行为是打破它们(使max_size成为硬限制).您可以通过将break_long_words = False传递给wrap()来更改为此处某些其他解决方案使用的软限制,在这种情况下,它将返回整个单词.如果您想要此行为,请将最后一行更改为:
lines = textwrap.wrap(text, max_size-3, break_long_words=False)
return lines[0] + ("..." if len(lines)>1 else "")
Run Code Online (Sandbox Code Playgroud)
根据您想要的确切行为,还有一些其他选项,如expand_tabs可能会引起您的兴趣.
def smart_truncate1(text, max_length=100, suffix='...'):
"""Returns a string of at most `max_length` characters, cutting
only at word-boundaries. If the string was truncated, `suffix`
will be appended.
"""
if len(text) > max_length:
pattern = r'^(.{0,%d}\S)\s.*' % (max_length-len(suffix)-1)
return re.sub(pattern, r'\1' + suffix, text)
else:
return text
Run Code Online (Sandbox Code Playgroud)
要么
def smart_truncate2(text, min_length=100, suffix='...'):
"""If the `text` is more than `min_length` characters long,
it will be cut at the next word-boundary and `suffix`will
be appended.
"""
pattern = r'^(.{%d,}?\S)\s.*' % (min_length-1)
return re.sub(pattern, r'\1' + suffix, text)
Run Code Online (Sandbox Code Playgroud)
要么
def smart_truncate3(text, length=100, suffix='...'):
"""Truncates `text`, on a word boundary, as close to
the target length it can come.
"""
slen = len(suffix)
pattern = r'^(.{0,%d}\S)\s+\S+' % (length-slen-1)
if len(text) > length:
match = re.match(pattern, text)
if match:
length0 = match.end(0)
length1 = match.end(1)
if abs(length0+slen-length) < abs(length1+slen-length):
return match.group(0) + suffix
else:
return match.group(1) + suffix
return text
Run Code Online (Sandbox Code Playgroud)
>>> import textwrap
>>> textwrap.wrap('The quick brown fox jumps over the lazy dog', 12)
['The quick', 'brown fox', 'jumps over', 'the lazy dog']
Run Code Online (Sandbox Code Playgroud)
你只需要采取第一个要素,你就完成了......
| 归档时间: |
|
| 查看次数: |
23173 次 |
| 最近记录: |