2014-01-16 73 views
1

我有文本的語料庫:含有各種句子和段落文件追加共同occurence鍵值

這裏是我的代碼:

import re 
import nltk 
from nltk.tokenize import RegexpTokenizer 
import math 
from collections import Counter 
with open("descriptionsample.tsv", "r") as openfile: 
frequency = Counter() 
stopwords = nltk.corpus.stopwords.words('english') 
tokenizer = RegexpTokenizer("[\w’]+", flags=re.UNICODE) 
for line in openfile: 
    words = line.lower().strip() 
    words=re.sub(r'[0-9]|\~|\`|\@|\#|\$|\%|\^|\&|\*|\(|\)|\_|\+|\=|\{|\[|\}|\]|\\|\<|\,|\<|\.|\>|\?|\/|\;|\:', '',words).replace('-',' ') 
    tokens = tokenizer.tokenize(words) 
    tokens = [token for token in tokens if token not in stopwords] 
    frequency.update(tokens) 

我的結果是在一個櫃檯格式

{'code':32344,'sql':2123,'chicago':1233...........} etc. 

但假設由文檔的第一行執行的字頻度的結果爲:

{'code':10,'sql':3,'python':2........} 

我想要做的是創建一個文件(而不是二元/三元組等)的元組共現矩陣,然後收集最後的總和。基本上將每個鍵的計數附加到由Key1,Key2創建的新創建的元組:Key2的值。 key2甚至可以是key1。

所以在TSV文件的每一行統計詞頻後,我希望通過線結果是這個樣子:

{('code','code'):10,('code','sql)':3,('code','python'):2,('sql,'code'):10,('sql','sql'):3,('sql','python'):2,('python','code'):10,('python','sql'):3,('python','python'):2} 

我無法弄清楚。任何幫助?也許我會忽略其他一些能自己做到這一點的圖書館。

回答

0

一位同事爲我弄明白了。我最初嘗試了嵌套字典的層和層,但遍歷它將是一場噩夢。因此,這是一個更簡單,更高效的解決我的問題:

doc2= { 
'a': 1, 
'b': 2, 
'c': 3, 
'd': 4, 
'e': 5 
} 

res = {} 

for key1 in doc2.keys(): 
    for key2 in doc2.keys(): 
     if key1 != key2: 
      res[(key1, key2)] = doc2[key2] 


for key in res: 
    print("[{}, {}] = {}".format(key[0], key[1], res[key])) 

結果:

[b, c] = 3 
[d, a] = 1 
[b, a] = 1 
[d, c] = 3 
[e, d] = 4 
[c, d] = 4 
[d, e] = 5 
[c, e] = 5 
[e, c] = 3 
[c, a] = 1 
[a, d] = 4 
[e, b] = 2 
[a, e] = 5 
[d, b] = 2 
[c, b] = 2 
[a, b] = 2 
[e, a] = 1 
[b, e] = 5 
[a, c] = 3 
[b, d] = 4