如何将nltk中的功能写入txt文件?

时间:2013-05-07 03:19:11

标签: python file machine-learning stdout nltk

我用nltk训练了一个天真的贝叶斯分类器。函数show_most_informative_featuressource code)可以将训练过程中的顶级似然特征打印到python shell,但它没有返回值。

enter image description here

现在我想将最丰富的功能写入txt文件。但是这些功能都是Unicode,包含中文/日文单词和一些特殊符号。我无法使用'>'将打印重定向到txt文件。

那么如何使用此函数将函数写入txt文件而不返回值?感谢。

2 个答案:

答案 0 :(得分:1)

请不要更改nltk库的源代码! 这真的是不好的做法。例如,如果您更新库,或者您需要与未相应修改其库的其他人共享您的代码,会发生什么?

图书馆的行为是标准化的原因!

对于您的问题,您具有等效功能

classifier.most_informative_features(n)

返回您训练的分类器的n个最具信息性的功能列表!!!!

答案 1 :(得分:0)

从源代码中简单改变。 (我不是试试。)

def show_most_informative_features(self, n=10):
    strlist = []
    # Determine the most relevant features, and display them.
    cpdist = self._feature_probdist
    # print('Most Informative Features')
    strlist.append('Most Informative Features')

    for (fname, fval) in self.most_informative_features(n):
            def labelprob(l):
                return cpdist[l,fname].prob(fval)
            labels = sorted([l for l in self._labels
                     if fval in cpdist[l,fname].samples()],
                    key=labelprob)
            if len(labels) == 1: continue
            l0 = labels[0]
            l1 = labels[-1]
            if cpdist[l0,fname].prob(fval) == 0:
                ratio = 'INF'
            else:
                ratio = '%8.1f' % (cpdist[l1,fname].prob(fval) /
                          cpdist[l0,fname].prob(fval))
            # print(('%24s = %-14r %6s : %-6s = %s : 1.0' %
            #      (fname, fval, ("%s" % l1)[:6], ("%s" % l0)[:6], ratio)))
            strlist.append(('%24s = %-14r %6s : %-6s = %s : 1.0' %
                          (fname, fval, ("%s" % l1)[:6], ("%s" % l0)[:6], ratio)))

    return strlist

# Useage
list = show_most_informative_features(classifier, 100)
file.writelines(list)

P.S。

请不要直接更改源代码!