2014-02-26 2 views
0

타겟 프로젝트의 단어를 둘러싼 창 메커니즘을 구현하고자하는 프로젝트 목적의 파이썬 코드를 작성했습니다. 아래 주어진 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) 

I는 '개'의 왼쪽에서 '개'와 (2)의 우측에서 단어 2리스트를 원하는 window_element 루프 타겟 워드는 기능에서 매우 '개'이기 먼저 실행 여기하자. 그러나 여기에는 개가 왼쪽에 아무런 단어도 없으므로 목록에는 아무 것도 포함되지 않으며 오른쪽에서 두 단어를 취하여 제대로 실행합니다.
이 방법을 원하지만 위의 방법으로는 할 수 없습니다. 아무도 내 요구 사항을 이행 할 선택적 메커니즘을 제안 할 수 있습니까?

+0

정확히 무엇을 원하십니까? 예를 들어주세요 – youssefhassan

+0

내 설명에 변화가 생겼는지 확인해주세요 – Madhusudan

+1

왜 함수에'ind' 인수를 넘겨 줍니까?하지만 함수 자체에서 전역'index'를 사용하고 있습니까? – geoffspear

답변

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 
+0

들여 쓰기를 검토하십시오. – jonrsharpe

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

왜 시도/예외 메카닉을 사용하지 않습니까?

def window_elements(win,ind,txt): 
    for i in (1, 2, -1, -2): 
     try: 
      win.append(txt[index + i]) 
     except IndexError: 
      pass 
    return win 
관련 문제