【问题标题】:Python: string.rfind() with any whitespace character?Python:带有任何空白字符的 string.rfind()?
【发布时间】: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 并有限制。然后你可以在末尾添加...

标签: python string


【解决方案1】:

这最适合使用正则表达式模式,该模式匹配非空白字符后跟最多 14 个字符(对于最多 15 个字符的块)和前瞻模式,以确保它们后跟空白字符或字符串的结尾:

import re
text = "This is just a text string for demonstrative purposes."
print(re.findall(r'\S.{,14}(?=\s|$)', text))

这个输出:

['This is just a', 'text string for', 'demonstrative', 'purposes.']

【讨论】:

    【解决方案2】:
        i = -1
        while (true):
            if chunk[i] in ['\n','\r','\t', ' ']:
                end = i
            else:
                i -= 1
            
    

    这样的东西对你有用吗?它将从末尾扫描块以查找任何空白字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-04
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      相关资源
      最近更新 更多