使用空格将字符串拆分为Python中具有最大长度的子字符串

时间:2017-12-04 03:07:24

标签: python string parsing text rss

我有一个这样的字符串:

Trump, Defending Himself After Flynn Guilty Plea, Says FBI Is in 'Tatters' | CVS to Buy Aetna for $69 Billion in a Deal that May Reshape the Health Industry | Joy Reid Apologizes for Past Anti-Gay Articles: 'Insensitive, Tone Deaf and Dumb' | California 18-year-old confesses to molesting dozens of children | Bill Belichick Apologizes for Rob Gronkowski's Late Hit, Calls It 'Bulls--t' | Met Opera Suspends James Levine After New Sexual Abuse Accusations | Like it or not, Alabama brings legitimacy to this year's College Football Playoff | Trump's campaign: Big Macs, screaming fits and constant rivalries | Manhattan equity director mauled to death by shark while scuba diving off Costa Rican coast | Man Stabs Two in Queens, Then Drives Into Their Helpers, Police Say | Here's how the Rangers might be able to separate themselves from other contenders for Shohei Ohtani | Alabama's Disdain for Democrats Looms Over Its Senate Race | Billy Bush confirms it was Trump's voice on 'Access Hollywood' tape: 'Yes, Donald Trump, you said that' | Andy Reid: Darrelle Revis didn't play in second half because he played a lot in first half | Geno Smith calls out 'coward' Rex Ryan: 'I saved his job' | Jimmy Garoppolo gives the 49ers exactly what they need, plus more Week 13 notes | Enter the 'Petro': Venezuela to Launch Oil-Backed Cryptocurrency | Wiring blamed in failed Pontiac Silverdome implosion | McConnell predicts unpopular tax bill will be a winning issue for GOP | Broncos drop eighth straight in ugly loss to Dolphins |

这是从Google新闻RSS Feed解析的新闻标题列表。我通过串口将数据发送到LCD,该LCD有2行,每行16个字符。目前,我将字符串拆分为32个字符部分,然后显示每个部分一段固定的时间。这个问题是它在大多数情况下只显示最后一个单词的一部分,在某些情况下,只显示第一个单词的一部分,具体取决于字符串的分割方式。那么,我如何通过空格分割字符串,以防止分割单词,并仍然尝试小于32个字符的限制。

使用上述文字的一个例子是:

第一线:特朗普,在

后捍卫自己

第二行:Flynn Guilty Plea,FBI表示

等等。

2 个答案:

答案 0 :(得分:3)

您可以按如下方式创建自己的定义和定义限制,您可以遍历列表。

str = "Trump, Defending Himself After Flynn Guilty Plea, Says FBI Is in 'Tatters'"

def split_string(str, limit, sep=" "):
    words = str.split()
    if max(map(len, words)) > limit:
        raise ValueError("limit is too small")
    res, part, others = [], words[0], words[1:]
    for word in others:
        if len(sep)+len(word) > limit-len(part):
            res.append(part)
            part = word
        else:
            part += sep+word
    if part:
        res.append(part)
    return res

print split_string(str=str, limit=32)

输出:

['Trump, Defending Himself After', 'Flynn Guilty Plea, Says FBI Is', "in 'Tatters'"]

答案 1 :(得分:0)

您正尝试将文本换行为32个字符的行长度。标准库中的textwrap模块执行此操作。