按数字拆分字符串

Splits a string by number

我刚刚编写了一个非常简单的函数,它按给定的数字拆分字符串。它有效,但有缺陷。它有时会把一个词分开,例如:

string = "He could not meet her in conversation"
number_of_lines = 5
result = (textwrap.fill(string, count(string, number_of_lines)))
print result

He could
not meet
her in c
onversat
ion

请注意它打断了单词 "conversation." 我需要有关如何解决此问题的建议,或者已经有针对此任务的内置函数可用。

这是实际的功能:

import textwrap
import re

def count (s, no_of_lines):
    result = (textwrap.fill(s.upper(), 1))
    count = 1  
    while (len(re.split('[\n]', result)) != no_of_lines):
        count = count + 1
        result = (textwrap.fill(s.upper(), count))
    return count

您可以使用 break_long_words option of the TextWrapper constructor:

import textwrap
import re

# define a customised object with option set to not break long words
textwrap = textwrap.TextWrapper(break_long_words=False)

def count (s, no_of_lines):
    # set the width option instead of using a count
    textwrap.width = 1
    result = textwrap.fill(s.upper())
    while len(re.split('\n', result)) > no_of_lines:
        textwrap.width += 1
        result = textwrap.fill(s.upper())
    return textwrap.width

string = "He could not meet her in conversation"
number_of_lines = 5
textwrap.width = count(string, number_of_lines)
result = textwrap.fill(string)
print (result)

输出:

He could
not meet
her in
conversation