将字符串每n个单词拆分为较小的字符串

4

情况: 我有一大段文本,想要将其拆分成更小的字符串。每n个单词为一个字符串。

text = "This is a small example Text, showcasing my desired output."

应该使用n = 4进行拆分:

textList = ['This is a small', 'example Text, showcasing my', 'desired output.']    

我的想法是使用以下方式将其拆分为仅包含单词的列表:

n = len(text)    
textList = text.split(' ', n)   

然后使用join()将其组合在一起,但我卡住了,因为:

for x in range(0, 3):
    ' '.join(textList)

没有将列表组合成我想要的输出


2
尝试使用re.findall(r'\W*(?:\w+\W+){1,4}', text) - Wiktor Stribiżew
2个回答

3

试试这个:

text = 'This is a small example Text, showcasing my desired output.'
text = text.split()
n = 4
[' '.join(text[i:i+n]) for i in range(0,len(text),n)]

0
text = "This is a small example Text, showcasing my desired output."

def split_sentence(texto):
    split_texto = texto.split()
    comb_st = [] # Combinaciones split
    i = 0
    for st in split_texto:
        comb_st.append(st)
        if split_texto == split_texto[-1]:
            break
        else:
            add_st = ""
            for cs2 in split_texto[i + 1: ]:
                add_st += " " + cs2
                add_st = add_st.lstrip()
                comb_st.append(st + " " + add_st)
        i += 1
    # for i in range(len(comb_st)):
    #     comb_st[i] = comb_st[i].split()
    return comb_st

comb_split_texto = split_sentence(text)

OUTPUT:
This
This is
This is a
This is a small
This is a small example
This is a small example Text,
This is a small example Text, showcasing
This is a small example Text, showcasing my
This is a small example Text, showcasing my desired
This is a small example Text, showcasing my desired output.
is
is a
is a small
is a small example
is a small example Text,
is a small example Text, showcasing
is a small example Text, showcasing my
is a small example Text, showcasing my desired
is a small example Text, showcasing my desired output.
a
a small
a small example
a small example Text,
a small example Text, showcasing
a small example Text, showcasing my
a small example Text, showcasing my desired
a small example Text, showcasing my desired output.
small
small example
small example Text,
small example Text, showcasing
small example Text, showcasing my
small example Text, showcasing my desired
small example Text, showcasing my desired output.
example
example Text,
example Text, showcasing
example Text, showcasing my
example Text, showcasing my desired
example Text, showcasing my desired output.
Text,
Text, showcasing
Text, showcasing my
Text, showcasing my desired
Text, showcasing my desired output.
showcasing
showcasing my
showcasing my desired
showcasing my desired output.
my
my desired
my desired output.
desired
desired output.
output.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接