在Python中,递归地将文本换行到一定数量的字符有什么简洁的方法? [关闭]

问题描述 投票:-3回答:4

我有这个字符串:

text = "abc def ghi jkl mno pqr stu vwx yz\nabc def ghi jkl mno pqr stu vwx yz"

我想把它包装成一个字符宽度(例如5),这样它就变成了:

abc d
ef gh
i jkl
 mno 
pqr s
tu vw
x yz
abc d
ef gh
i jkl
 mno 
pqr s
tu vw
x yz

非递归,这​​是我得到的:

text_in  = text.split("\n")
text_out = []

width = 5
for line in text_in:
    if len(line) < width:
        text_out.append(line)
    else:
        text_out.append(line[:width])
        text_out.append(line[width:])

print("\n".join(text_out))

因此,它只对领先的订单级别有所帮助:

abc d
ef ghi jkl mno pqr stu vwx yz
abc d
ef ghi jkl mno pqr stu vwx yz

如何以递归或其他一些整洁的方式完成这种包装?

python textwrapping
4个回答
0
投票

正则表达式解决方案:

import re

def wrap_text(text, width):
    if not width:
        return text
    else:
        return re.sub(r'(.{' + str(width) + '})', '\\1\n', text)

text = "abc def ghi jkl mno pqr stu vwx yz\nabc def ghi jkl mno pqr stu vwx yz"

  • (.{<width>}) - 将每个<width>字符数捕获到第一个带括号的组(...)

测试案例#1:

print(wrap_text(text, 5))

输出:

abc d
ef gh
i jkl
 mno 
pqr s
tu vw
x yz
abc d
ef gh
i jkl
 mno 
pqr s
tu vw
x yz

测试案例#2:

print(wrap_text(text, 10))

输出:

abc def gh
i jkl mno 
pqr stu vw
x yz
abc def gh
i jkl mno 
pqr stu vw
x yz

1
投票

丹尼尔罗斯曼建议使用textwrap.wrap怎么了?刚刚完成,因为它消失了:

import textwrap

a = "abc def ghi jkl mno pqr stu vwx yz\nabc def ghi jkl mno pqr stu vwx yz"

for item in textwrap.wrap(a, 5):
    print(item)

1
投票

我会用列表理解来做到这一点:

text = "abc def ghi jkl mno pqr stu vwx yz\nabc def ghi jkl mno pqr stu vwx yz"

res = [text[pos:pos+5] for pos in range(0, len(text), 5)]

for i in res:
    print(i)

要处理新行字符,您可以使用额外的空格替换新行:

text = text.replace("\n", " ")

或列表理解后:

for i in res:
    if '\n' in i:
       i = i.strip('\n')
       print(i)
    else:
       print(i)

结果现在是:

abc d
ef gh
i jkl
 mno 
pqr s
tu vw
x yz
abc d
ef gh
i jkl
 mno 
pqr s
tu vw
x yz

-1
投票

可以使用for循环来获取子串:

text = "abc def ghi jkl mno pqr stu vwx yz\nabc def ghi jkl mno pqr stu vwx yz"
llen = len(text);     lst = [];     stemp = ""
for i in range(llen):
    if i % 5 == 0 and i>0:
        lst.append(stemp)
        stemp = ""
        stemp += text[i]
    else: 
        stemp += text[i]

for ll in lst: 
    print(ll)

输出:

abc d
ef gh
i jkl
 mno 
pqr s
tu vw
x yz

abc d
ef gh
i jkl
 mno 
pqr s
tu vw
© www.soinside.com 2019 - 2024. All rights reserved.