gpt4 book ai didi

Python Textwrap - 强制 'hard' 中断

转载 作者:行者123 更新时间:2023-12-01 06:16:48 26 4
gpt4 key购买 nike

我正在尝试使用 textwrap 来格式化导入文件,该文件的格式化方式非常特殊。基本上如下(为简单起见,缩短了行长):

abcdef <- Ok line
abcdef
ghijk <- Note leading space to indicate wrapped line
lm

现在,我的代码如下:

wrapper = TextWrapper(width=80, subsequent_indent=' ', break_long_words=True, break_on_hyphens=False)
for l in lines:
wrapline=wrapper.wrap(l)

这几乎完美地工作,但是,文本换行代码不会在 80 个字符标记处进行硬中断,它会尝试智能地在空格处中断(大约 20 个字符处)。

我已经通过用唯一字符(#)替换字符串列表中的所有空格,将它们换行然后删除该字符来解决这个问题,但是肯定有更干净的方法吗?

注意:任何可能的答案都需要在 Python 2.4 上工作 - 抱歉!

最佳答案

基于生成器的版本可能是您更好的解决方案,因为它不需要立即将整个字符串加载到内存中:

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

关于Python Textwrap - 强制 'hard' 中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2865250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com