Python中的块字符串,不会破坏单词

时间:2015-08-30 10:19:36

标签: python raspberry-pi

我有这个代码,用于在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案例。

3 个答案:

答案 0 :(得分:8)

使用textwrap模块:

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

答案 1 :(得分:1)

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.给出的答案后,使用该答案。始终使用库而不是微不足道的尝试重新发明轮子。总是

答案 2 :(得分:0)

使用生成器:

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!