Creating a dictionary of words and their context in a sentence

I have a Python list containing hundreds of thousands of words. Words appear in the order in which they appear in the text.

I want to create a dictionary of each word associated with a line containing that word, with 2 (say) words that appear before and after it.

For example, a list: "This" "is a" "example" "sentence"

Should become a dictionary:

"This" = "This is an"
"is" = "This is an example"
"an" = "This is an example sentence"
"example" = "is an example sentence"
"sentence" = "an example sentence"

Sort of:

WordsInContext = Dict()
ContextSize = 2
wIndex = 0
for w in Words:
    WordsInContext.update(w = ' '.join(Words[wIndex-ContextSize:wIndex+ContextSize]))
    wIndex = wIndex + 1

This may contain a few syntax errors, but even if they have been fixed, I am sure it will be a shockingly inefficient way to do this.

Can someone suggest a more optimized method?

+3
source share
2 answers

My suggestion:

words = ["This", "is", "an", "example", "sentence" ]

dict = {}

// insert 2 items at front/back to avoid
// additional conditions in the for loop
words.insert(0, None)
words.insert(0, None)
words.append(None)
words.append(None)

for i in range(len(words)-4):   
    dict[ words[i+2] ] = [w for w in words[i:i+5] if w]
+4
source
>>> from itertools import count
>>> words = ["This", "is", "an", "example", "sentence" ]
>>> context_size = 2
>>> dict((word,words[max(i-context_size,0):j]) for word,i,j in zip(words,count(0),count(context_size+1)))
{'This': ['This', 'is', 'an'], 'is': ['This', 'is', 'an', 'example'], 'sentence': ['an', 'example', 'sentence'], 'example': ['is', 'an', 'example', 'sentence'], 'an': ['This', 'is', 'an', 'example', 'sentence']}

In python 2.7+or3.x

{word:words[max(i-context_size,0):j] for word,i,j in zip(words,count(0),count(context_size+1))}
0
source

All Articles