gpt4 book ai didi

python - 有限的文本 block 被新行分割

转载 作者:行者123 更新时间:2023-12-01 03:08:00 26 4
gpt4 key购买 nike

我有一个 python 字符串,其中包含一个大文本文件(超过 1MiB)。我需要将它分成 block 。

限制:

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

可以省略长度超过 LIMIT 的行。

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

提前谢谢您。

最佳答案

按照 Linuxios 的建议,你可以使用 rfind 来查找限制内的最后一个换行符并在此时分割。如果没有找到换行符,则该 block 太大,可以忽略。

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] 以便换行符包含在 block 中

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

关于python - 有限的文本 block 被新行分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43149637/

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