【问题标题】:How can I add a newline after an amount of nonspace characters?如何在大量非空格字符后添加换行符?
【发布时间】:2020-01-17 20:45:52
【问题描述】:

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

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

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

【问题讨论】:

  • 如果我没看错this,你可以说for i in list(filter(lambda x: x !=" ", range(0, len(line), K)))
  • @RobertHarvey 没有工作,运行没有错误但没有效果。
  • 这仍然是我所追求的方法。

标签: python file-io character newline


【解决方案1】:

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

... 这是您想要计算剥离和内脏字符串中的字符,但将换行应用于原始字符串。解决这个问题的方法是用一条有点折磨的链来维护这两个索引。您需要计算字母和空格;当letter 达到K 的倍数时,您将生成的 chunk 从上一个终点向上传送到 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.

【讨论】:

    【解决方案2】:

    像@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.'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 2013-05-04
      • 2016-05-31
      • 1970-01-01
      • 1970-01-01
      • 2022-06-11
      • 2015-10-30
      相关资源
      最近更新 更多