4

这是我的一些代码:

def breakUp(x,chunk_size):
    return [ x[i:i+chunk_size] for i in range(0, len(x), chunk_size) ]

这是它的工作原理:

In [8]: breakUp('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!',10)

Out[8]: 
['This is a ',
 'cool sente',
 'nce... How',
 ' about eat',
 'ing it??? ',
 'Whats more',
 '?? pepper ',
 'is availab',
 'le all for',
 ' free!!!']

但正如你在第二个元素中看到的那样,句子这个词没有被完全理解,它说“sente”......

我知道这是因为我已经要求 python 在每 10 个字符之后分割它......无论如何指定我想在每 10 个字符之后分割,但是如果是第 10 个字符。以一个词结尾,取整个词...?

4

1 回答 1

6

电池包括:

>>> import textwrap
>>> print textwrap.fill('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!', 15)
This is a cool
sentence... How
about eating
it??? Whats
more?? pepper
is available
all for free!!!

这几乎可以满足您的所有要求。除了如果您指定10为第二个参数,它仍然会拆分,sentence...因为无法将其放入 10 个字符中。但是,如果你想这样做,你可以自textwrap定义break_long_words=False

>>> print textwrap.fill('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!', 10, break_long_words=False)
This is a
cool
sentence...
How about
eating
it???
Whats
more??
pepper is
available
all for
free!!!
于 2013-10-28T13:25:23.460 回答