我正在构建一个文字处理器,并尝试实现自动换行功能。
给定一行中的最大字符数,后跟单词列表,我想返回一个字符串集合,其中每行包含尽可能多的由空格连接的单词。每个字符串的长度不能超过最大长度。
- 输出的每个字符串中的每个单词之间必须恰好有一个空格。
- 每个单词都由英文字母表中的小写字母组成。
- 不会有标点符号。
- 可以假设每个单词的最大长度是恒定的。
- 单个单词的长度不会超过给定的一行字符最大长度。
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
最佳答案
这里有几个问题 -
最重要的是您正在读取 stdin 中的第一行,并将其用作 lineLength
,但您不将其转换为数字。因此,您在 lineLength
中的值(和包装函数内的 line_length
)变量是一个字符串 - 以及比较
if len(curr_line) + len(word) >= line_length:
始终将左侧建议的输出行的长度与字符串进行比较 - 如果您使用最新版本的 Python,则此行会出错,因为现在(正确地)禁止将数字和字符串合并。然而,在 Python 3 中,此表达式始终为 True - 编号始终被视为 <
比字符串 - 因此超出限制的行的代码永远不会运行。
第二个错误只是您没有将空格连接到行字符串,而只是将单词与 +=
连接起来。但不要添加空格。
第三个错误是您总是打印循环内计算的行 - 无论是否超出行长度。
最后但并非最不重要的 - 正如我在上面的评论中所说:不要再使用 Python 2 - 他们制作 Python 3 是有原因的,这是因为语言的发展。
而且,错误较少,但建议:您的函数应该只处理文本,并返回数据 - 如果您想打印结果,您可以从调用者函数中打印它。通过这种方式,该函数仍然足够通用,可以在其他上下文中使用。
此外,Python 应用程序的建议缩进大小为 4。虽然使用 2 个空格是有效的代码,但实际上没有在任何地方使用它(但在一些知名公司的私有(private)代码中 - 但这是他们的事)。
您的固定代码以及建议 - 将在 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()
关于python - 具有自动换行功能的 Python 文字处理函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55506885/