Python Sliding Window on sentence string

后端 未结 3 822
渐次进展
渐次进展 2021-01-15 10:53

I\'m looking for a sliding window splitter of string composed with words with window size N.

Input: \"I love food and I like drink\" , window size 3

3条回答
  •  半阙折子戏
    2021-01-15 11:37

    You can use iterator with different offsets and zip all of them.

    >>> arr = "I love food. blah blah".split()
    >>> its = [iter(arr), iter(arr[1:]), iter(arr[2:])] #Construct the pattern for longer windowss
    >>> zip(*its)
    [('I', 'love', 'food.'), ('love', 'food.', 'blah'), ('food.', 'blah', 'blah')]
    

    You might want to use izip if you have long sentences, or may be plain old loops (like in the other answer).

提交回复
热议问题