我有一个1000个字符长的文本字符串,我希望将这个文本拆分成小于100个字符的块而不分割整个单词(99个字符很好但100个没有)。包装/拆分应仅在空格上进行:
示例:
text = "... this is a test , and so on..."
^
#position: 100
应分为:
newlist = ['... this is a test ,', ' and so on...', ...]
我希望将文本列表newlist
正确拆分为可读(非文字裁剪)块。你会怎么做?
答案 0 :(得分:3)
您可以使用textwrap模块:
In [2]: import textwrap
In [3]: textwrap.wrap("""Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
...: tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
...: quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
...: consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
...: cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
...: proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
""", 40)
Out[3]:
['Lorem ipsum dolor sit amet, consectetur',
'adipisicing elit, sed do eiusmod tempor',
'incididunt ut labore et dolore magna',
'aliqua. Ut enim ad minim veniam, quis',
'nostrud exercitation ullamco laboris',
'nisi ut aliquip ex ea commodo consequat.',
'Duis aute irure dolor in reprehenderit',
'in voluptate velit esse cillum dolore eu',
'fugiat nulla pariatur. Excepteur sint',
'occaecat cupidatat non proident, sunt in',
'culpa qui officia deserunt mollit anim',
'id est laborum.']
答案 1 :(得分:3)
使用textwrap模块的wrap功能。下面的例子将10行宽的行分开:
In [1]: import textwrap
In [2]: textwrap.wrap("... this is a test , and so on...", 10)
Out[2]: ['... this', 'is a test', ', and so', 'on...']
答案 2 :(得分:0)
Wordwrap就像其他人说的那样,但是有另一种选择:
def splitter(s, n):
for start in range(0, len(s), n):
yield s[start:start+n]
data = "abcdefghijabcdefghijabcdefghijabcdefghijabcdefghij"
for splitee in splitter(data, 10):
print splitee