Reputation: 465
I am writing a python code for my project purpose in which I want to implement windowing mechanism (surrounding words of a target word) and I have written following part for it with an axample lists given below. I am getting "Index out of range" when target word is not surrounded by minimum two words on both the sides.
Window = list()
text = ['dog','bark','tree']
polysemy = ['dog','bark','tree']
def window_elements(win,ind,txt):
win.append(txt[index + 1])
win.append(txt[index + 2])
win.append(txt[index - 1])
win.append(txt[index - 2])
return win
for w in polysemy:
window = list()
index = text.index(w)
window = window_elements(window,index,text)
Suppose here for first execution of for loop target word is 'dog' so from function window_element I want a list of words 2 from the right side of 'dog' and 2 from left side of 'dog'. But here there are no words on the left side of dog so that list will not contain anythong for it and it will take two words from right side only and execute properly.
I want this mechanism but unable to do it in above manner. Can anyone suggest me optional mechanism which will fulfill my requirement?
Upvotes: 0
Views: 133
Reputation: 315
Why not just use try/except mechanic?
def window_elements(win,ind,txt):
for i in (1, 2, -1, -2):
try:
win.append(txt[index + i])
except IndexError:
pass
return win
Upvotes: 1
Reputation:
You can try following function. It will work fine.
def window_elements(win,ind,txt):
if(len(txt) == 1):
return
elif(ind == 0 and len(txt) == 2):
win.append(txt[1])
elif(ind == 1 and len(txt) == 2):
win.append(txt[0])
elif(ind == 0):
win.append(txt[index + 1])
win.append(txt[index + 2])
elif(ind == (len(txt) - 1)):
win.append(txt[index - 1])
win.append(txt[index - 2])
elif(ind == 1 and len(txt) < 4):
win.append(txt[index - 1])
win.append(txt[index + 1])
elif(ind == (len(txt) - 2) and len(txt) >= 4):
win.append(txt[index + 1])
win.append(txt[index - 1])
win.append(txt[index - 2])
elif(ind >= 2 or ind <= (len(txt) - 3)):
win.append(txt[index + 1])
win.append(txt[index + 2])
win.append(txt[index - 1])
win.append(txt[index - 2])
return win
Upvotes: 1
Reputation: 121966
You can use slicing for this:
def window(lst, index):
return lst[max(0,index-2):index+3]
For example:
>>> for i in range(10):
print(i, window(list(range(10)), i))
0 [0, 1, 2]
1 [0, 1, 2, 3]
2 [0, 1, 2, 3, 4]
3 [1, 2, 3, 4, 5]
4 [2, 3, 4, 5, 6]
5 [3, 4, 5, 6, 7]
6 [4, 5, 6, 7, 8]
7 [5, 6, 7, 8, 9]
8 [6, 7, 8, 9]
9 [7, 8, 9]
Slicing will "fail gracefully" if the upper index is out of bounds, returning as much as it can.
Upvotes: 3