Python Textwrap-forcing';硬的';打破
我正在尝试使用textwrap格式化一个导入文件,该文件的格式非常特殊。基本上如下所示(为简单起见,缩短了行长度): 这几乎完美地工作,但是,文本包装代码不会在80个字符的标记处进行硬中断,它尝试在一个空格(大约20个字符)上进行智能中断 我已经用一个唯一的字符(#)替换了字符串列表中的所有空格,将它们包装,然后删除该字符,但肯定有更干净的方法吗Python Textwrap-forcing';硬的';打破,python,python-2.x,word-wrap,python-2.4,Python,Python 2.x,Word Wrap,Python 2.4,我正在尝试使用textwrap格式化一个导入文件,该文件的格式非常特殊。基本上如下所示(为简单起见,缩短了行长度): 这几乎完美地工作,但是,文本包装代码不会在80个字符的标记处进行硬中断,它尝试在一个空格(大约20个字符)上进行智能中断 我已经用一个唯一的字符(#)替换了字符串列表中的所有空格,将它们包装,然后删除该字符,但肯定有更干净的方法吗 注意:任何可能的答案都需要在Python2.4上使用-抱歉 听起来好像您正在禁用TextWrapper的大部分功能,然后尝试添加一点您自己的功能。我认
注意:任何可能的答案都需要在Python2.4上使用-抱歉 听起来好像您正在禁用TextWrapper的大部分功能,然后尝试添加一点您自己的功能。我认为您最好编写自己的函数或类。如果我没弄错的话,你只是在寻找长度超过80个字符的行,然后在80个字符的标记处打断它们,然后将剩余的行缩进一个空格 例如,这:
s = """\
This line is fine.
This line is very long and should wrap, It'll end up on a few lines.
A short line.
"""
def hard_wrap(s, n, indent):
wrapped = ""
n_next = n - len(indent)
for l in s.split('\n'):
first, rest = l[:n], l[n:]
wrapped += first + "\n"
while rest:
next, rest = rest[:n_next], rest[n_next:]
wrapped += indent + next + "\n"
return wrapped
print hard_wrap(s, 20, " ")
产生:
This line is fine.
This line is very lo
ng and should wrap,
It'll end up on a
few lines.
A short line.
基于生成器的版本可能是更好的解决方案,因为它不需要一次在内存中加载整个字符串:
def hard_wrap(input, width, indent=' '):
for line in input:
indent_width = width - len(indent)
yield line[:width]
line = line[width:]
while line:
yield '\n' + indent + line[:indent_width]
line = line[indent_width:]
像这样使用它:
from StringIO import StringIO # Makes strings look like files
s = """abcdefg
abcdefghijklmnopqrstuvwxyz"""
for line in hard_wrap(StringIO(s), 12):
print line,
其中打印:
abcdefg
abcdefghijkl
mnopqrstuvw
xyz
from StringIO import StringIO # Makes strings look like files
s = """abcdefg
abcdefghijklmnopqrstuvwxyz"""
for line in hard_wrap(StringIO(s), 12):
print line,
abcdefg
abcdefghijkl
mnopqrstuvw
xyz