我正在为我的项目目的编写一个python代码,我想在其中实现窗口机制(目标词的周围单词),并且我已经用下面给出的axample列表编写了以下部分。当目标词没有被两边最少两个字包围时,我得到“索引超出范围”。
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)
假设这里第一次执行for循环目标词是'dog'所以从函数window_element我想要一个单词列表2来自'dog'的右侧和2来自'dog'的左侧。但是在这里,狗的左侧没有任何单词,因此列表不会包含任何内容,只会从右侧获取两个单词并正确执行。
我想要这种机制,但无法以上述方式进行。任何人都可以建议我满足我的要求的可选机制吗?
答案 0 :(得分:3)
您可以使用切片:
def window(lst, index):
return lst[max(0,index-2):index+3]
例如:
>>> 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]
如果上层索引超出范围,切片将“优雅地失败”,尽可能多地返回。
答案 1 :(得分:1)
您可以尝试以下功能。它会工作正常。
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
答案 2 :(得分:1)
为什么不使用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