【问题标题】:How to truncate a string in python including a truncated word in the result?如何截断python中的字符串,包括结果中的截断单词?
【发布时间】:2022-07-05 16:51:11
【问题描述】:

Truncate a string without ending in the middle of a word 这里有一个关于如何在 python 中进行“智能”字符串截断的精彩讨论。 但是这里提出的解决方案的问题是,如果宽度限制在一个词内,那么这个词就被完全抛弃了。

如何在 python 中截断字符串设置“软”宽度限制,即如果限制落在单词的中间,那么这个单词被保留?

例子:

str = "it's always sunny in philadelphia"
trunc(str, 7)
>>> it's always...

我最初的想法是将字符串切片到软限制,然后开始检查每个下一个字符,将其添加到切片中,直到遇到空白字符。但这似乎效率极低。

【问题讨论】:

    标签: python string


    【解决方案1】:

    怎么样:

    def trunc(ipt, length, suffix='...'):
      if " " in ipt[length-1: length]:
        # The given length puts us on a word boundary
        return ipt[:length].rstrip(' ') + suffix
    
      # Otherwise add the "tail" of the input, up to just before the first space it contains
      return ipt[:length] + ipt[length:].partition(" ")[0] + suffix
    
    s = "it's always sunny in philadelphia"  # Best to avoid 'str' as a variable name, it's a builtin
    for n in (1, 4, 5, 6, 7, 12, 13):
      print(f"{n}: {trunc(s, n)}")
    

    哪个输出:

    1: it's...
    4: it's...
    5: it's...
    6: it's always...
    7: it's always...
    12: it's always...
    13: it's always sunny...
    

    注意第 5 和第 12 种情况的行为:此代码假定您要消除“...”之前出现的空格。

    【讨论】:

    • str 变量命名的好点,出于某种原因,我认为内置函数是 string
    • 然后我调用了一个参数input :D 现在修复了!
    【解决方案2】:

    不知何故,我错过了 Markus Jarderot 在链接帖子 here 中提供的答案

    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)
    

    运行时间

    3.49 µs ± 25.7 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)

    @slothrop 的解决方案适用于:

    897 ns ± 3.27 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

    这样比较快

    【讨论】:

      猜你喜欢
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 2011-10-02
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多