Reputation: 428
I have a Python list containing hundreds of thousands of words. The words appear in the order they are in the text.
I'm looking to create a dictionary of each word associated with a string containing that word with 2 (say) words that appear before and after it.
For example the list: "This" "is" "an" "example" "sentence"
Should become the 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"
Something like:
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 those were corrected, I'm sure it would be a hideously inefficient way of doing this.
Can someone suggest a more optimized method please?
Upvotes: 3
Views: 1421
Reputation: 133574
>>> 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+
or 3.x
{word:words[max(i-context_size,0):j] for word,i,j in zip(words,count(0),count(context_size+1))}
Upvotes: 0
Reputation: 5919
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]
Upvotes: 5