Search code examples
arrayspython-3.xnumpyn-gram

Verify that a word exists in a list of Context


i have a function that divide a phrase into contexts with a window(length of how to divide it) example : it was the best of times it was the worst of times we find 10 contexts so this my the result

the results of my function

my code

text = 'it was the best of times it was the worst of times '
#text1='c etait le meilleur des temps'
phrase = text.split()

def PhraseToContexts(phrase, window):     
      return [phrase[i:i+window] for i in range(len(phrase)-(window-1))]
print(PhraseToContexts(phrase, 3))

PS: i'm using python (spyder)

now, what i want is to create another function named oneContext(listContexts,phrase,word,window) that verify if this word exist in the list of contexts and return a vector contain the value 1 to say the word exists in context, 0 else.

in the same previous example if we search about "it" the vector that we obtain is [1.0.0.0.0.0.1.0.0.0]

enter image description here


Solution

  • def oneContext(listContexts,phrase,word): 
        l = [1 if word in x[int(len(x)/2)] else 0 for x in listContexts]
        return l
    

    where,

    listContexts = PhraseToContexts(phrase, window)