python - 带有自动换行的 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
解决方案
那里有几个问题 - 最重要的一个是您正在阅读 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()
推荐阅读
- c# - 如何更改验证器上的语言
- c# - 将字节数组转换为图片(c# => VB6)
- .htaccess - 将随机数/哈希码保存在 .htacces 文件中或为用户访问的每个网页分别创建随机随机数/哈希码是否安全?
- css - CSS - 在选项卡上创建可见边框
- javascript - 尝试在后端nodejs服务器上验证它时在js chrome扩展中生成令牌时出错
- python - 从抓取的数据中拆分 html (Python+BeautifulSoup4)
- r - R - 移动多行并相应地扩展矩阵
- python - 为什么不同格式的响应会有所不同?
- openssl - openssl 发行者/主题格式差异
- python - 如何使用证书和证书密钥对 url 进行身份验证?