创建单词及其句子上下文的字典

Vel*_*ost 3 python

我有一个包含数十万个单词的 Python 列表。单词按照它们在文本中的顺序出现。

我希望为每个单词创建一个字典,该字典与包含该单词的字符串相关联,并且在该单词之前和之后出现 2 个(比如说)单词。

例如列表:“This”“is”“an”“example”“sentence”

应该成为字典:

"This" = "This is an"
"is" = "This is an example"
"an" = "This is an example sentence"
"example" = "is an example sentence"
"sentence" = "an example sentence"
Run Code Online (Sandbox Code Playgroud)

就像是:

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

这可能包含一些语法错误,但即使这些错误得到纠正,我确信这将是一种极其低效的方法。

有人可以建议一个更优化的方法吗?

Dir*_*irk 5

我的建议:

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]
Run Code Online (Sandbox Code Playgroud)