2013-06-22 13 views
-1

我有一個字典,是以下形式:連接一個字典到另一個在python

​​

例如:

d[earn]=(6,7,4) 

其中6.txt,7.txt和4.txt是屬於類文件「賺」

現在,我需要創建另一個字典D2這樣的:

d2[earn]=(12,3,2,17) 

其中

  • 12處於6.txt發生的次數的詞「賺」的數量,
  • 3是倍單詞「獲得」發生在7.txt數,
  • 4是4.txt中單詞「賺」的次數
  • 17是在所有三個文件中出現單詞「賺」的次數,即;總和。

這裏是我的代碼:

import collections 
import sys 
import os 
import re 
sys.stdout=open('dictionary.txt','w') 
from collections import Counter 
from glob import glob 


folderpath='d:/individual-articles' 
counter=Counter() 

with open('topics.txt') as f: 
    d= collections.defaultdict(list) 
    for line in f: 
     value, *keys = line.strip().split('~') 
     for key in filter(None, keys): 
      d[key].append(value+".txt") 

filepaths = glob(os.path.join(folderpath,'*.txt')) 

def words_generator(fileobj): 
    for line in fileobj: 
     for word in line.split(): 
      yield word 
word_count_dict = {} 
for file in filepaths: 
    f = open(file,"r") 
    words = words_generator(f) 
    for word in words: 
     if word not in word_count_dict: 
       word_count_dict[word] = {"total":0} 
     if file not in word_count_dict[word]: 
       word_count_dict[word][file] = 0 
     word_count_dict[word][file] += 1    
     word_count_dict[word]["total"] += 1   
for k in word_count_dict.keys(): 
    for filename in word_count_dict[k]: 
     if filename == 'total': continue 
     counter.update(filename) 

for word, counts in word_count_dict.items(): 
    print(word, counts['total']) 

我需要打印D2,但我的代碼不能正常工作。

回答

0

我想這應該做你要找的內容:

from collections import defaultdict 
d2 = defaultdict(list) 
for word,files in d.items(): 
    for fname in files: #go over each file name in the 'list' which was associated with the key 'word' in d 
     with open(fname) as f: 
      d2[word].append(f.read().count(word)) #add the count of the word in the file 
      #d2[word].append(f.read().split().count(word)) use this if you want words not occurances of 'word' in the file 
    d2[word].append(sum(d2[word])) #add the sum of all the counts 
print d2 
+0

注意'f.read()數(字)'可以有意想不到的結果爲:' 「foobar的」 .Count之間(」 foo') - > 1',更喜歡'regex'。 –

+0

@AshwiniChaudhary是的,我意識到發佈後,在它下面添加了一個'f.read()。split()。count(word)'方式。使用正則表達式可能會更好,OP可以研究這一點。 – HennyH

+0

我得到這個錯誤:文件「C:\ Python33 \ access_dict.py」,行36,在 與開放(fname)作爲f: FileNotFoundError:[Errno 2]沒有這樣的文件或目錄:'16951' – radhika

相關問題