Python 在句子中创建单词及其上下文词典

Python 在句子中创建单词及其上下文词典,python,Python,我有一个包含数十万单词的Python列表。这些词在文本中的出现顺序 我正在寻找创建一个与字符串相关联的每个单词的字典,该字符串包含两个(比如)出现在单词前后的单词 例如列表:“This”是一个“示例”句子 应该成为字典: "This" = "This is an" "is" = "This is an example" "an" = "This is an example sentence" "example" = "is an example sentence" "sentence" = "a

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

我正在寻找创建一个与字符串相关联的每个单词的字典,该字符串包含两个(比如)出现在单词前后的单词

例如列表:“This”是一个“示例”句子

应该成为字典:

"This" = "This is an"
"is" = "This is an example"
"an" = "This is an example sentence"
"example" = "is an example sentence"
"sentence" = "an example sentence"
比如:

WordsInContext = Dict()
ContextSize = 2
wIndex = 0
for w in Words:
    WordsInContext.update(w = ' '.join(Words[wIndex-ContextSize:wIndex+ContextSize]))
    wIndex = wIndex + 1
这可能包含一些语法错误,但即使这些错误得到纠正,我相信这将是一种效率极低的方法

有人能推荐一种更优化的方法吗?

我的建议:

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]
在python中
2.7+
3.x

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

你知道你会用这样的句子改写条目吗?为了快速随机存取,你把清单>代码>作为你的第一部分(如果你必须再次访问该列表,例如索引(10),索引(1212)。否则,你可能会考虑<代码>集合。DeQue/Coo>。唯一的问题是链接列表(实际上是双链)。.List是
数组
,因此它不是用于随机访问的。另外,
deveque
是一个双端队列……但是,如果您的
List
非常大(数万个),则
deveque
可能会很有用你一次只能遍历一个。但我不认为遍历链表比在现代编译器下遍历数组更糟糕。我的2美分。@eumiro:是的,我意识到我会重写句子,那应该没问题。我只需要一个单词的“上下文”。如果你
[w for w in words[I:I+5]if w]
,输出应该正是OP想要的。+1对于一个优雅的解决方案@Dirk!@DarenThomas:我在哪里使用[w for w in words[I:I+5]如果w]?事实上,我决定不需要存储上下文。我只需要将其写入一个文件。按照您的代码,我尝试了类似这样的东西:wPos=firewardslist.index(w);对于FireOrdsList中的cw[wPos-ContextSize:wPos+ContextSize+1]:f2.写入(cw+“”)。我感觉“索引”将进行线性搜索,速度非常慢。有更好的方法吗?试试这个:对于范围内的I(len(words)-4):对于单词中的w[I:I+5]:如果w:f2.写入(w+“”)f2.写入(“\n”)
{word:words[max(i-context_size,0):j] for word,i,j in zip(words,count(0),count(context_size+1))}