1

I have a text and want to pass a sliding window over it using the code from Rolling or sliding window iterator in Python and I have spaces in the text, so instead of how it currently works if n ==4,

input = 'Hello my name is Steven'

output = ['hell','ello','llo ','lo m','o my',' my ','my n',...]

I want it to basically ignore the spaces so the output looks like this:

output = ['hell','ello','my','name','is','Stev','teve','even']

how would I go about doing this?

Community
  • 1
  • 1
hsifyllej
  • 45
  • 3

2 Answers2

0

You can filter the above output and reduce the desired output.

print [i.strip(' ') for i in output if not i.strip(' ').count(' ')]

Output:

['hell','ello','my','name','is','Stev','teve','even']
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
0

Slight modification (added if in window()) of the accepted answer in the post you mentioned and then applying the function in each item can produce what you want.

Code with working example can be seen here

from itertools import islice

def window(seq, n=4):
    if len(seq)<n:
      yield seq
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result    
    for elem in it:
        result = result[1:] + (elem,)
        yield result

result = []
input = 'Hello my name is Steven'
for item in input.split():
  result.extend(list(window(item)))

result = map(lambda x: ''.join(x), result)
print result
themistoklik
  • 880
  • 1
  • 8
  • 19