【问题标题】:Word wrap algorithm not printing as expected自动换行算法未按预期打印
【发布时间】:2014-06-03 06:34:40
【问题描述】:

我想开发一种递归自动换行算法,它采用指定的字符串和换行长度(一行上的最大字符数)来返回输入长度的换行输出。我不希望它分解单词。例如,长度为 20 的 This is the first paragraph that you need to input 返回为:

This is the first
paragraph that you
need to input

但是,我的函数当前打印:

This is the first paragraph
that you need to input

我的代码:

def wrap(text, lineLength):

    temp=text.find(" ",lineLength-1)
    if temp == -1:
        return text
    else:
        return text[:temp+1]+'\n'+wrap(text[temp+1:], lineLength)

print wrap("This is the first paragraph that you need to input", 20);

为什么这不符合我的预期,我该如何解决?

【问题讨论】:

  • 我不知道你是在做这个练习,还是真的在尝试实现它,但 Python 确实有一个模块:docs.python.org/2.7/library/textwrap.html
  • 这确实是为了我自己的利益的练习,但我也对内置模块感到好奇。谢谢!

标签: python algorithm recursion word-wrap


【解决方案1】:

通过一些更改,您的代码可以正常工作:

def wrap(text, lineLength):
    if len(text) <= lineLength: return text
    temp = text.rfind(" ", 0, lineLength - 1)
    if temp == -1: 
        return text
    else:
        return text[:temp+1]+'\n'+wrap(text[temp+1:], lineLength)

有了这个输出:

This is the first 
paragraph that you 
need to input

但您可能还想在没有空间可中断时强制使用连字符:

def wrap(text, lineLength):
    if len(text) <= lineLength: return text
    temp = text.rfind(" ", 0, lineLength - 1)
    if temp == -1: 
        return text[:lineLength - 1] + '-\n' + wrap(
            text[lineLength - 1:], lineLength)
    else:
        return text[:temp+1] + '\n' + wrap(text[temp+1:], lineLength)

print wrap("Thisisthefirstparagraphthatyouneed to input", 20)

这会导致:

Thisisthefirstparag-
raphthatyouneed to 
input

【讨论】:

  • 太棒了,谢谢!我正在研究算法,所以我很高兴这个问题主要是语法和极端情况。
【解决方案2】:

您正在使用 find 并将 start 参数设置为 19,这意味着您在第 20 个字符之后找到 first 空格 。你想要的是找到 last 空格 before 第 20 个字符。看看改用rfind

【讨论】:

  • 酷,谢谢。我的 Python 技能不再像以前那样了:/
【解决方案3】:

在不完全了解您使用的是哪种自动换行算法的情况下,我怀疑这很时髦:

temp=text.find(" ",lineLength-1)
if temp == -1:
    return text

如果您在第一个 lineLength-1 字符中没有找到空格,则只需逐字返回文本。你不需要在那里递归吗?

【讨论】:

  • 这实际上不是问题的原因,尽管它是代码的另一个潜在问题。
  • 看起来很合理。您发现的一个错误可能是错误行为的主要原因,但大多数“自动换行”的定义似乎终止条件显然是错误的。
【解决方案4】:
def wrap(str,l):     
    ll=list(str)
    i=l
    while i < len(str):
        ll.insert(i,"\n")
        i=i+l
    nstr="".join(ll)
    print nstr

输出: 这是第一次

你喜欢的照片

需要输入

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多