首页 > 解决方案 > 带有自动换行的 Python 文字处理函数

问题描述

我正在构建一个文字处理器,并试图实现自动换行功能。

给定一行中的最大字符数,后跟一个单词列表,我想返回一个字符串集合,其中每行包含尽可能多的单词,并用空格连接。每个字符串的长度不应超过最大长度。

import sys

# Prints to standard output.
def wrapLines(line_length, words):
  curr_line = ""
  for word in words:
    if len(curr_line) + len(word) >= line_length:
      curr_line = ""
    else:
      curr_line += word
      print curr_line


def main():
  first_line = None
  words = []

  first_arg = True
  for line in sys.stdin:
    if len(line.strip()) == 0:
      continue

    line = line.rstrip()

    if first_arg:
      lineLength = line
      first_arg = False
    else:
      words.append(line)

  wrapLines(lineLength, words)

main()

输入:

13
abc
xyz
foobar
cuckoo
seven
hello

我的输出不断打印所有相互连接的单词,而不是换行。

abc
abcxyz
abcxyzfoobar
abcxyzfoobarcuckoo
abcxyzfoobarcuckooseven
abcxyzfoobarcuckoosevenhello

预期输出:

abc xyz
foobar cuckoo
seven hello

标签: pythonstringlistfunctionword-wrap

解决方案


那里有几个问题 - 最重要的一个是您正在阅读 stdin 中的第一行,并将其用作lineLength,但您没有将其转换为 number。因此,您在 lineLength(以及line_length包装函数内部)变量中的值是一个字符串 - 并且比较

 if len(curr_line) + len(word) >= line_length:

始终将左侧建议的输出行的长度与字符串进行比较 - 如果您使用最新版本的 Python,则此行会出错,因为现在(正确地)禁止使用数字和字符串。然而,在 Python 3 中,此表达式始终为 True - 编号始终被视为 <字符串 - 因此超出限制的行的代码永远不会运行。

第二个错误只是你没有将空格连接到你的行字符串 yu 只是将单词连接起来+=但不添加空格。

第三个错误是您总是打印循环内正在计算的行 - 无论是否超过行长。

最后,但并非最不重要的——正如我在上面的评论中所说:不要再使用 Python 2——他们制作 Python 3 是有原因的,这是因为语言进化了。

而且,错误较少​​,但建议:您的函数应该只处理文本并返回数据 - 如果您想打印结果,您可以从调用者函数打印它。通过这种方式,该函数保持足够的通用性,可以在其他上下文中使用。

此外,Python 应用程序的推荐缩进大小为 4。虽然使用 2 个空格是有效代码,但它实际上并没有在任何地方使用(但在一些知名公司的私有代码中 - 但这是他们的业务)。

您的固定代码,加上推荐 - 将在 Python 2 和 3 中工作:

import sys

def wrapLines(line_length, words):
    curr_line = ""
    result = []
    for word in words:
        if len(curr_line) + len(word) + 1 >= line_length:
            result.append(curr_line)
            curr_line = ""
        else:
            curr_line += " " + word
    if curr_line:
        result.append(currline)
    return result


def main():
    first_line = None
    words = []

    first_arg = True
    for line in sys.stdin:
        if len(line.strip()) == 0:
            continue

        line = line.rstrip()

        if first_arg:
            line_length = int(line)
            first_arg = False
        else:
            words.append(line)

    print("\n".join(wrapLines(line_length, words)))


main()

推荐阅读