将类少的代码转换为类结构

时间:2016-02-24 10:18:50

标签: python class

我在字典中添加了一些值。 原始代码没有类,所以我写了类并尝试运行相同的代码。这给出了错误。

原始代码:https://gist.github.com/anonymous/2da54d3db5b867529fd8

class MyDict(dict):
    def __getitem__(self, key):
        if key in self:
            return self.get(key)
        return 0

pos = MyDict()
neg = MyDict()

我应该在哪里定义pos,如果我使用类结构则为neg?

新代码 - https://gist.github.com/anonymous/b0e84df9a05f165ea2dd

错误在for循环的第4行

def train(self):
    global pos, neg, totals
    retrain = False

    # Load counts if they already exist.
    if not retrain and os.path.isfile(CDATA_FILE):
        pos, neg, totals = cPickle.load(open(CDATA_FILE))
        return

    limit = 12500
    for file in os.listdir("./aclImdb/train/pos")[:limit]:
        for word in set(self.negate_sequence(open("./aclImdb/train/pos/" + file).read())):
            pos[word] += 1
            neg['not_' + word] += 1
    for file in os.listdir("./aclImdb/train/neg")[:limit]:
        for word in set(self.negate_sequence(open("./aclImdb/train/neg/" + file).read())):
            neg[word] += 1
            pos['not_' + word] += 1

我收到此错误:

Traceback (most recent call last):
  File "sentiment_worker.py", line 144, in <module>
    MyDict().gearman_worker.work()
  File "sentiment_worker.py", line 26, in __init__
    self.train()
  File "sentiment_worker.py", line 76, in train
    pos[word] += 1
KeyError: 'all'

1 个答案:

答案 0 :(得分:1)

你在第二个版本中使用了dict类型的pos,它会导致无效键的错误。

pos = dict()

第一个版本有MyDict,它检查密钥是否存在,并返回0表示无效密钥。

pos = MyDict()

你可以使用

from collections import defaultdict
pos = defaultdict(lambda: 0)