【问题标题】:limited text chunks splitted by new line由新行分割的有限文本块
【发布时间】:2017-03-31 21:04:07
【问题描述】:

我在 python 中有一个包含大文本文件(超过 1MiB)的字符串。 我需要把它分成块。

约束:

  • 块只能由换行符分割,并且
  • len(chunk) 必须尽可能大但小于 LIMIT(即 100KiB)

可以省略超过 LIMIT 的行。

知道如何在 python 中很好地实现这一点吗?

提前谢谢你。

【问题讨论】:

  • 要拆分成一个新文件?
  • 没时间把它写出来,但最好的解决办法可能是跳到 LIMIT,向后工作直到找到换行符,添加一个块,再从那里向前跳 LIMIT,然后重复。

标签: python split newline chunks


【解决方案1】:

按照 Linuxios 的建议,您可以使用 rfind 找到限制内的最后一个换行符并在此时拆分。如果没有找到换行符,则块太大并且可以被关闭。

chunks = []

not_chunked_text = input_text

while not_chunked_text:
    if len(not_chunked_text) <= LIMIT:
        chunks.append(not_chunked_text)
        break
    split_index = not_chunked_text.rfind("\n", 0, LIMIT)
    if split_index == -1:
        # The chunk is too big, so everything until the next newline is deleted
        try:
            not_chunked_text = not_chunked_text.split("\n", 1)[1]
        except IndexError:
            # No "\n" in not_chunked_text, i.e. the end of the input text was reached
            break
    else:
        chunks.append(not_chunked_text[:split_index+1])
        not_chunked_text = not_chunked_text[split_index+1:]

rfind("\n", 0, LIMIT) 返回在 LIMIT 范围内找到换行符的最高索引。
需要not_chunked_text[:split_index+1] 以便将换行符包含在块中

我将 LIMIT 解释为允许的最大块长度。如果不应允许长度为 LIMIT 的块,则必须在此代码中的 LIMIT 之后添加 -1

【讨论】:

    【解决方案2】:

    这是我不那么 Pythonic 的解决方案:

    def line_chunks(lines, chunk_limit):
        chunks = []
        chunk = []
        chunk_len = 0
        for line in lines:
            if len(line) + chunk_len < chunk_limit:
                chunk.append(line)
                chunk_len += len(line)
            else:
                chunks.append(chunk)
                chunk = [line]
                chunk_len = len(line)
        chunks.append(chunk)
        return chunks
    
    chunks = line_chunks(data.split('\n'), 150)
    print '\n---new-chunk---\n'.join(['\n'.join(chunk) for chunk in chunks])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 2010-10-31
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      相关资源
      最近更新 更多