-1

I want to split the texts into 2-2-2 words as I mentioned in the title. but i cant do that

song= ["Rolling in the deep wish you"]
iwantformat_output=["Rolling in", "the deep", "wish you"]

song= ["Rolling in the deep wish you"]
a=song.split(" ")

The crazy thing I tried was to replace 1 space with 2 space characters in split(" ") i have no more idea

C.Nivs
  • 12,353
  • 2
  • 19
  • 44

3 Answers3

0

I don't know why you have an array of a single string.

Here's my solution, using numpy's reshape:

import numpy as np
song = "Rolling in the deep wish you"
pairs = [" ".join(k) for k in np.reshape(song.split(" "), (-1, 2))]
print(pairs)

I don't know any method that doesn't involve splitting every word and then stitching them back together.

if you don't want to use numpy, you could try this:

song = "Rolling in the deep wish you"
song_words = song.split(" ")
pairs = [" ".join(song_words[i:i+2]) 
         for i in range(0, len(song_words)-1, 2)]
print(pairs)
['Rolling in', 'the deep', 'wish you']

but you have to be careful about edge cases, i.e. what do you get if your input has an even or odd number of words.

chw21
  • 7,970
  • 1
  • 16
  • 31
0
song = "Rolling in the deep wish you" 
song_split = song.split(' ')
iwantformat_output = [" ".join(song_split[i:i+2]) for i in range(0, len(song_split), 2)]
GTS
  • 550
  • 5
  • 7
0
import re
re.findall('[^ ]+ [^ ]+', song)
Andrey
  • 400
  • 2
  • 8