0

let's say I have a string

s = 'Hello world, I am Foo. I like dogs'

I want to parse thru this string and extract words in groups of x. Let's say x = 3, my output should be:

out = ['Hello world, I', 'world, I am', 'I am Foo.', 'am Foo. I', 'Foo. I like', 'I like dogs']

Is there a way to do this? I tried this code but it's very bad.

    sss = s.split()
    x = 3
    for i, word in enumerate(sss):
        for j in range(x):
            extract = sss[j+i:x+j]
            print(extract)

out: ['Hello', 'world,', 'I']
['world,', 'I', 'am']
['I', 'am', 'Foo.']
['world,', 'I']
['I', 'am']
['am', 'Foo.']
['I']
['am']
['Foo.']
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
user12195705
  • 147
  • 2
  • 10

1 Answers1

3
s = 'Hello world, I am Foo. I like dogs'

words = s.split()
x = 3
results = [
    ' '.join(words[i:i + x])
    for i in range(len(words) - x + 1)
]
print(results)

output:

['Hello world, I', 'world, I am', 'I am Foo.', 'am Foo. I', 'Foo. I like', 'I like dogs']
Boseong Choi
  • 2,566
  • 9
  • 22