хорошо, это правда, класс автовивации пропал, вместо этого пошел по умолчанию, кажется лучше

аюсь создать обратный индекс документа, поэтому мне нужно знать из всех уникальных слов в коллекции, в каком документе они встречаются и как часто.

я использовалэто ответьте по порядку два создайте вложенный словарь. Предоставленное решение прекрасно работает, хотя с одной проблемой.

Сначала я открываю файл и составляю список уникальных слов. Эти уникальные слова я хочу сравнить с оригинальным файлом. Когда есть совпадение, счетчик частоты должен быть обновлен, и его значение должно быть сохранено в двумерном массиве.

вывод должен в конечном итоге выглядеть следующим образом:

word1, {doc1 : freq}, {doc2 : freq} <br>
word2, {doc1 : freq}, {doc2 : freq}, {doc3:freq}
etc....

Проблема в том, что я не могу обновить переменную словаря. При попытке сделать это я получаю сообщение об ошибке:

  File "scriptV3.py", line 45, in main
    freq = dictionary[keyword][filename] + 1
TypeError: unsupported operand type(s) for +: 'AutoVivification' and 'int'

Я думаю, что мне нужно каким-то образом привести экземпляр AutoVivification к int ....

Как пройти?

заранее спасибо

мой код:

#!/usr/bin/env python 
# encoding: utf-8

import sys
import os
import re
import glob
import string
import sets

class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

def main():
    pad = 'temp/'
    dictionary  = AutoVivification()
    docID = 0
    for files in glob.glob( os.path.join(pad, '*.html') ):  #for all files in specified folder:
        docID = docID + 1
        filename = "doc_"+str(docID)
        text = open(files, 'r').read()                      #returns content of file as string
        text = extract(text, '<pre>', '</pre>')             #call extract function to extract text from within <pre> tags
        text = text.lower()                                 #all words to lowercase
        exclude = set(string.punctuation)                   #sets list of all punctuation characters
        text = ''.join(char for char in text if char not in exclude) # use created exclude list to remove characters from files
        text = text.split()                                 #creates list (array) from string
        uniques = set(text)                                 #make list unique (is dat handig? we moeten nog tellen)

        for keyword in uniques:                             #For every unique word do   
            for word in text:                               #for every word in doc:
                if (word == keyword and dictionary[keyword][filename] is not None): #if there is an occurence of keyword increment counter 
                    freq = dictionary[keyword][filename]    #here we fail, cannot cast object instance to integer.
                    freq = dictionary[keyword][filename] + 1
                    print(keyword,dictionary[keyword])
                else:
                    dictionary[word][filename] = 1

#extract text between substring 1 and 2 
def extract(text, sub1, sub2): 
    return text.split(sub1, 1)[-1].split(sub2, 1)[0]    

if __name__ == '__main__':
    main()

Ответы на вопрос(9)

Ваш ответ на вопрос