Flexible sliding window (in Python)

Problem Description: . I am interested in viewing terms in a text box, say 3 words on the left and 3 words on the right. The main body has the form w-3 w-2 w-1 term w + 1 w + 2 w + 3. I want to implement a sliding window above my text, with which I can write down the contextual words of each term. Thus, each word is considered as a term, but when the window moves, it becomes a context word, etc. However, when the term is the 1st word in the line, there are no contextual words on the left side (tw + 1 w + 2 w + 3), when this is the second word in the line, there is only one contextual word on the left, etc. Therefore, I am interested in any recommendations for implementing this flexible sliding window (in Python) without writing and specifying each possible situation separately.

Repeat:

Input Example :

["w1", "w2", "w3", "w4", "w5", "w6", "w7", "w8", "w9", "w10"]

Output :

t1 w2 w3 w4

w1 t2 w3 w4 w5

w1 w2 t3 w4 w5 w6

w1 w2 w3 t4 w5 w6 w7

__ w2 w3 w4 t5 w6 w7 w8

__ __ etc.

My current plan is to implement this with a separate condition for each line in the output.

+3
source share
1 answer

If you want a sliding word box n, use a bidirectional queue with maximum length nto implement the buffer.

This should illustrate the concept:

mystr = "StackOverflow"    
from collections import deque    
window = deque(maxlen=5)
for char in mystr:
    window.append(char)
    print ( ''.join(list(window)) )

Conclusion:

S
St
Sta
Stac
Stack
tackO
ackOv
ckOve
kOver
Overf
verfl
erflo
rflow
+5
source

All Articles