def fprob(self, f, cat): if self.catcount(cat) == 0: return 0 #notice: rember change int to double or float # + 0.0 or *1.0 is ok, other wise, may get 0. return self.fcount(f, cat) * 1.0 / self.catcount(cat)
def prob(self, item, cat): #notice: take care of *1.0 or + 0.0 catprob = self.catcount(cat)*1.0/self.totallcount() docprob = self.docprob(item, cat) return docprob * catprob
def fcount(self, f, cat = None): #get the count of f in all cats if cat == None: if f not in self.fc: return 0 return sum(self.fc[f].values()) #get the count of f labeled cat else: if f in self.fc and cat in self.fc[f]: return self.fc[f][cat] return 0
def loadText(textfile = 'a.txt'): text = [] f = open(textfile) lines = f.readlines() for line in lines: #delete the '\n' at the end line line = line.strip('\n') text.append(line) f.close() return text
def loadCat(catfile = 'b.txt'): cat = [] f = open(catfile) lines = f.readlines() for line in lines: line = line.strip('\n') cat.append(line) f.close() return cat
《集体智慧编程》代码勘误:第六章,布布扣,bubuko.com
原文地址:http://blog.csdn.net/shiquxinkong/article/details/33386753