截断字符串而不以单词中间结尾 [英] Truncate a string without ending in the middle of a word

查看:22
本文介绍了截断字符串而不以单词中间结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在 Python 中截断字符串的方法,该方法不会切断单词中间的字符串.

例如:

<前>原文:这真是太棒了."哑巴"截断:这是真的……"聪明"截断:这真是……"

我正在寻找一种方法来完成上面的智能"截断.

解决方案

实际上,我在我最近的一个项目中为此编写了一个解决方案.我已将其中的大部分压缩得更小.

def smart_truncate(content, length=100, suffix='...'):如果 len(content) <= 长度:返回内容别的:return ' '.join(content[:length+1].split(' ')[0:-1]) + 后缀

if 语句会检查您的内容是否已经小于截止点.如果不是,它会截断到所需的长度,在空间上拆分,删除最后一个元素(这样你就不会切断一个单词),然后将它重新连接在一起(同时添加...").

I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.

For example:

Original:          "This is really awesome."
"Dumb" truncate:   "This is real..."
"Smart" truncate:  "This is really..."

I'm looking for a way to accomplish the "smart" truncate from above.

解决方案

I actually wrote a solution for this on a recent project of mine. I've compressed the majority of it down to be a little smaller.

def smart_truncate(content, length=100, suffix='...'):
    if len(content) <= length:
        return content
    else:
        return ' '.join(content[:length+1].split(' ')[0:-1]) + suffix

What happens is the if-statement checks if your content is already less than the cutoff point. If it's not, it truncates to the desired length, splits on the space, removes the last element (so that you don't cut off a word), and then joins it back together (while tacking on the '...').

这篇关于截断字符串而不以单词中间结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆