【问题标题】:chunk string in Python without breaking wordsPython中的块字符串而不破坏单词
【发布时间】:2015-08-30 10:19:36
【问题描述】:

我有这段代码,用于在 20x2 LCD 显示器上显示一些文本:

#!/usr/bin/python

LCDCHARS = 20
LCDLINES = 2

def WriteLCD(text_per_LCD):
    chunked = (text_per_LCD[i:LCDCHARS+i] for i in range (0, len(text_per_LCD), LCDCHARS))
    count_l = 0
    for text_per_line in chunked:
        # print will be replaced by actual LCD call
        print (text_per_line)
        count_l += 1
        if count_l >= LCDLINES:
            # agree to lose any extra lines
            break

WriteLCD("This text will display on %s LCD lines" % (LCDLINES))

示例字符串将输出

This text will displ
ay on 2 LCD lines

我应该怎么做才能在不破坏单词的情况下拆分字符串?即使第二行变得更长并且不再显示,这也是如此。

我在javascript sectionruby section 上阅读了一个类似的问题,但我无法将给定的答案翻译成我的 Python 案例。

【问题讨论】:

    标签: python raspberry-pi


    【解决方案1】:

    使用textwrap 模块:

    >>> textwrap.wrap("This text will display on 3 LCD lines", 20)
    ['This text will', 'display on 3 LCD', 'lines']
    

    【讨论】:

    • 虽然我实际使用了这个解决方案,但我仍然有一个困境,正如我在与darkryder solution 相关的其他评论中所表达的那样。
    【解决方案2】:
    YOUR_STRING = "This text will display on 10 LCD lines"
    CHAR_LIMIT = 25 # anything
    

    首先,让我们从找出断点(在您的情况下为空格)开始。

    让我们使用来自https://stackoverflow.com/a/11122355/2851353的函数

    def find(s, ch):
        return [i for i, ltr in enumerate(s) if ltr == ch]
    
    breakpoints = find(YOUR_STRING, " ")
    # [4, 9, 14, 22, 25, 28, 32]
    

    现在,我们找到单词的索引,直到我们可以安全地拆分句子。

    让我们从https://stackoverflow.com/a/2236956/2851353找到另一个函数

    def element_index_partition(points, breakpoint):
        return [ n for n,i in enumerate(points) if i>breakpoint ][0]
    
    best = element_index_partition(breakpoints, CHAR_LIMIT)
    

    现在,我们只需要拆分并重新加入字符串。

    # We won't go till `best` (inclusive) because the function returns the next index of the partition
    first_str = " ".join(YOUR_STRING.split(" ")[:best])
    last_str =  " ".join(YOUR_STRING.split(" ")[best:])
    

    编辑 看到 Dan D. 给出的答案后,使用该答案。始终使用库,而不是尝试重新发明轮子。总是。

    【讨论】:

    • 关于“始终使用库而不是尝试重新发明轮子”,我在这里有点怀疑:就运行程序时的整体效率而言,考虑到函数的特殊情况在相对较长(> 1000 行)的整个程序代码中只需要一次,是否可以只导入一个(更多)库以简化我的几行代码(如 Dan D. 答案中的textwrap),或者是为了避免导入库,最好使我的本地代码复杂一点?所以就在那时,如果函数调用需要不止一次(假设这是可预见的)。
    • 当标准库一举解决您的需求时,就去做吧。它将经过很好的测试,被世界上的其他人使用,将处理晦涩的角落案例。但最好的是,对于未来的维护者和您自己来说,含义会更加清晰。
    【解决方案3】:

    使用生成器:

    LCDCHARS = 20
    LINE = "This text will display on 2 LCD lines No more!"
    LCDLINES = 2
    
    def split_line(line):
        words = line.split()                                                                                                                               
        l = ""
        # Number of lines printed
        i = 0
        for word in words:
            if i < LCDLINES - 1 and len(word)+ len(l) > LCDCHARS:
                yield l.strip()
                l = word
                i += 1
            else:
                l+= " " + word
        yield l.strip()
    
    for line in split_line(LINE):
        print line
    

    输出:

    This text will
    display on 2 LCD lines No more!
    

    【讨论】:

    • OP 只想要两行,即使它跑到一边。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 2013-10-01
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    相关资源
    最近更新 更多