【发布时间】:2021-01-28 12:37:36
【问题描述】:
我正在尝试将文本拆分成块以发送到 Google 的文本转语音引擎(每个查询最多接受 5000 个字符)。我想在最大长度为 5000 个字符的空白字符上拆分较长的文件。我当前的代码(使用 15 而不是 5000 的块大小):
def split_text(text) -> list:
start = 0
chunk_size = 15
chunk = ''
chunks = []
chunks_remaining = True
while chunks_remaining:
end = start + chunk_size
if end >= len(text):
chunks_remaining = False
chunk = text[start:end]
end = chunk.rfind(' ') + start
chunks.append(text[start:end] + "...")
start = end+1
return chunks
def main():
text = "This is just a text string for demonstrative purposes."
chunks = split_text(text)
print(chunks)
有没有办法用接受任何空白字符的东西替换chunk.rfind(' ')?
【问题讨论】:
-
这在 javascript 中使用正则表达式,但应该很容易移植到 python:stackoverflow.com/a/49836804
-
您可以反转字符串并使用
re.split并有限制。然后你可以在末尾添加...。