在Python中分块字符串,不分割单词

2024-09-29 06:26:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码,它是用来在20x2液晶显示器上显示一些文本的:

#!/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))

将输出示例字符串

^{pr2}$

我该怎么做才能在不破坏单词的情况下拆分字符串?即使第二行变长并退出显示。在

我在javascript section上读到了一个类似的问题,而在ruby section中又读到了另一个问题,但我无法将给出的答案翻译成我的Python案例。在


Tags: 字符串textinforlcdcountlinewill
3条回答
YOUR_STRING = "This text will display on 10 LCD lines"
CHAR_LIMIT = 25 # anything

首先,让我们先找出断点(在您的例子中是空格)。在

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

^{pr2}$

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

让我们从中找到另一个函数: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给出的答案后,使用该答案。总是使用库,而不是做一些无力的尝试来重新发明轮子。总是这样。在

使用发电机:

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

输出:

^{pr2}$

使用^{}模块:

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

相关问题 更多 >