我写了一个小脚本,在达到某个字符限制后创建一个新的换行符。现在问题是脚本从文本末尾开始输出文本。我似乎无法弄清楚如何在不使脚本更复杂的情况下以正确的顺序打印文本。我这样做是为了更好地理解递归。
以下是代码:
def insertNewlines(text, lineLength):
if len(text) <= lineLength:
return text
else:
return insertNewlines(text[lineLength:], lineLength) + '\n' + text[:lineLength]
以下是lineLength为15的测试输出:
length.
e desired line
s or exceeds th
ord that reache
n' after each w
e character '\
Insert a newlin
ewriter would.
e text as a typ
length, wrap th
a desired line
Given text and
实际输入:
text = "Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character '\\n' after each word that reaches or exceeds the desired line length."
编辑: 根据下面的建议修改了代码,以便正确包装单词:
if len(text) <= lineLength:
return text
elif text[lineLength] != ' ':
return insertNewlines(text[:], lineLength + 1)
else:
return text[:lineLength] + '\n' + insertNewlines(text[lineLength + 1:], lineLength)
以下是新输出:
给出文字和一个
所需的线长,
将文本包装为打字机
将。插入换行符字符
&#39; \ n&#39;在达到
的每个单词之后
或超过所需的线长。
答案 0 :(得分:4)
如果您不希望以最大宽度剪切字词,请尝试textwrap
库,请参阅http://docs.python.org/2/library/textwrap.html
from textwrap import TextWrapper
text = "Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character '\\n' after each word that reaches or exceeds the desired line length."
tw = TextWrapper()
tw.width = 20
print "\n".join(tw.wrap(text))
<强> [OUT]:强>
Given text and a
desired line length,
wrap the text as a
typewriter would.
Insert a newline
character '\n'
after each word that
reaches or exceeds
the desired line
length.
这是一个原生的python实现:
text = "Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character '\\n' after each word that reaches or exceeds the desired line length."
def wrap(txt, width):
tmp = ""
for i in txt.split():
if len(tmp) + len(i) < width:
tmp+=" "+i
else:
print tmp.strip()
tmp = i
wrap(text, 20)
更加pythonic yield
方法:
def wrap(txt, width):
tmp = ""
for i in txt.split():
if len(tmp) + len(i) < width:
tmp+=" "+i
else:
yield tmp.strip()
tmp = i
print "\n".join(i for i in wrap(text, 20))
答案 1 :(得分:1)
问题在于递归调用的顺序。它应该在功能的尾部,以实现你想要的。试试这个:
def insertNewlines(text, lineLength):
if len(text) <= lineLength:
return text
else:
return text[:lineLength] + '\n' + insertNewlines(text[lineLength:], lineLength)
text = "Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character '\\n' after each word that reaches or exceeds the desired line length."
print insertNewlines(text, 15)
输出:
Given text and
a desired line
length, wrap th
e text as a typ
ewriter would.
Insert a newlin
e character '\
n' after each w
ord that reache
s or exceeds th
e desired line
length.