繁体   English   中英

如何在一定数量的非空格字符后添加换行符?

[英]How can I add a newline after an amount of nonspace characters?

我正在尝试在一定数量的字符后添加换行符并使其正常工作。

outfile.write('\n'.join(line[i:i+K] for i in range(0,len(line), K)))

我想修改它,以便不计算空格(非空格数量后的换行符)。

我已经对该主题进行了一些研究,但还没有找到一个优雅的解决方案。 这个问题有一些表亲,解决方案涉及textwrap几个答案,但没有什么能解决你的核心问题......

...这就是你想计算一个去内脏的字符串中的字符数,但将换行符应用到原始字符串中。 对此的解决方案将是一个有点折磨的链来维护这两个索引。 你需要计算字母和空格; letter达到K的倍数时,您将生成的从上一个终点到 line[letter_count+space_count] 沿线向上馈送。

坦率地说,我认为为未来的编码人员编写、调试、维护和(尤其是)文档是不值得的。 只需编写循环以遍历您的行。 这是痛苦的长版本:

line = "Now is the time for all good parties to come to the aid of man." + \
       "  It was the best of times, it was the worst of times."
K = 20

slugs = []
left = 0
count = 0
for idx, char in enumerate(line):
    if char != ' ':
        count += 1
    if count == K:
        count = 0
        slugs.append(line[left: idx+1])
        left = idx+1

slugs.append(line[left:])
print ('\n'.join(slugs))

输出:

Now is the time for all go
od parties to come to the
 aid of man.  It was the bes
t of times, it was the wor
st of times.

像@Prune 一样,我还没有找到一种优雅的方法来优雅地使用任何现有的内置模块来完成它——所以这是一种(另一种)手动完成的方法。

它的工作原理是从给定的可迭代对象创建一个由 K 个非空格字符组成的组列表,并在处理完其中的所有字符后返回该列表。

def grouper(iterable, K):
    nonspaced = []
    group = []
    count = 0
    for ch in iterable:
        group.append(ch)
        if ch != ' ':
            count += 1
            if count == 4:
                nonspaced.append(''.join(group))
                group = []
                count = 0
    if group:
        nonspaced.append(''.join(group))

    return nonspaced


K = 4
line = "I am trying to add a newline after a certain amount of characters."
for group in grouper(line, K):
    print(repr(group))

输出:

I am t'
'ryin'
'g to a'
'dd a n'
'ewli'
'ne af'
'ter a'
' cert'
'ain a'
'moun'
't of c'
'hara'
'cter'
's.'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM