我有一堆文本样本。每个样本有不同的长度,但它们都由>200个字符组成。我需要把每个样本分成大约50个chara的长度子串。为此,我发现了以下方法:
import re
def chunkstring(string, length):
return re.findall('.{%d}' % length, string)然而,它通过分裂单词来分割文本。例如,短语“我有<...> icecream. <...>”可以分为"I into <...> icec“和"ream. <...>”。
这是示例文本:
本文提出了一种通过使用一种名为StarGAN的生成对抗性网络的变体来实现非并行多到多语音转换的方法。
我得到了这个结果:
['This paper proposes a method that allows non-paral',
'lel many-to-many voice conversion by using a varia',
'nt of a generative adversarial network called Star']但理想情况下,我希望得到类似于这样的结果:
['This paper proposes a method that allows non-parallel',
'many-to-many voice conversion by using a variant',
'of a generative adversarial network called StarGAN.']如何调整上述给定的代码以获得所需的结果?
发布于 2021-08-04 14:42:02
对于我来说,这听起来像textwrap内置模块的任务,例如使用您的数据。
import textwrap
text = "This paper proposes a method that allows non-parallel many-to-many voice conversion by using a variant of a generative adversarial network called StarGAN."
print(textwrap.fill(text,55))输出
This paper proposes a method that allows non-parallel
many-to-many voice conversion by using a variant of a
generative adversarial network called StarGAN.你可能需要一些试验才能得到最适合你需求的价值。如果需要list of str的话,请使用textwrap.wrap,即textwrap.wrap(text,55)
发布于 2021-08-04 14:32:11
您可以使用.{0,50}\S*来继续匹配最终的非空间字符(\S)。
我将0指定为低界,因为否则可能会丢失最后一个子字符串。
参见演示这里。
编辑:
为了排除尾随空块,请使用.{1,50}\S*,以强制它至少匹配一个字符。
如果您还想自动删除边框,请使用\s*(.{1,50}\S*)。
发布于 2022-09-25 14:32:33
def nearestDelimiter(txt, cur):
delimiters = " ;:.!?-—"
if(txt[cur] in delimiters) :
return cur
else:
i=cur
while ( i>=0 ):
if (txt[i] in delimiters) :
return i
i=i-1
return 0
def splitText(sentence,chunkLength):
cursor = 0
curlng = chunkLength
lst = []
while (curlng < len(sentence)):
curlng = nearestDelimiter(sentence, curlng)
substr = (sentence[cursor : curlng]).strip()
cursor = curlng
curlng = (cursor+chunkLength) if (cursor+chunkLength<len(sentence)) else len(sentence)
lst.append(substr)
lst.append((sentence[cursor : curlng]).strip())
return lst
txt = "This paper proposes a method that allows non-parallel many-to-many voice conversion by using a variant of a generative adversarial network called StarGAN."
cvv = splitText(txt,50)
for cv in cvv:
print(cv)https://stackoverflow.com/questions/68652956
复制相似问题