2012-04-20 60 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))}