2012-04-20 34 views
3

我有一个包含数十万单词的Python列表。单词按照它们在文本中的顺序出现。在句子中创建单词词典及其上下文

我正在创建一个字典,每个单词与一个包含该单词的字符串相关联,其中有2个(说)单词出现在它之前和之后。

例如名单: “这”, “是”, “一个”, “例子”, “句子”

应该成为词典:

"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 

这可能包含一些语法错误,但即使这些错误已得到纠正,我相信这将是一个非常低效的方法。

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

+1

* *您知道*您*会用这样的句子一个覆盖项? – eumiro 2012-04-20 07:31:12

+0

对于快速随机访问,你把'list'为您的第一部分(如果你再次访问该列表,例如指数(10),指数(1212)。否则,你可能会考虑'collections.deque'。该唯一的问题是这是一个链表(实际上是double),List是'array',所以它不是用于随机访问的。另外,'deqeue'是一个双端队列....但是,'deqeue'可能是有用的,如果你有真正的大'list'(几万),你只走一次一个,但我不认为遍历链表是正走在现代化的编译器阵列的那样糟糕。我2美分 – CppLearner 2012-04-20 07:47:32

+0

@eumiro:是的,我知道我会被改写句子,这应该是罚款所有我需要的是一个单词的一个“语境” – 2012-04-20 07:58:14

回答

4

我的建议:

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] 
+1

,如果你做'[W为w的字[我。 :i + 5] if w]',输出结果应该与OP想要的一样。+1为优雅的解决方案@Dirk! – 2012-04-20 08:05:34

+0

@DarenThomas:我在哪里使用[w for w [ :我+ 5]如果W]? – 2012-04-20 08:07:47

+0

啊没关系。这个小问题很好的解决方案。 – Dirk 2012-04-20 08:10:46

0
>>> 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']} 

在蟒蛇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))}