0

我已经下载并清理了一组 RSS 提要,用作带有 NLTK 的语料库,用于测试分类。但是当我运行频率分布时,许多顶级结果似乎是特殊字符:

<FreqDist: '\x92': 494, '\x93': 300, '\x97': 159, ',\x94': 134, 'company': 124, '.\x94': 88, 'app': 84, 'Twitter': 82, 'people': 76, 'time': 73, ...>

我在这里尝试了问题中的建议并因此初始化了语料库(指定编码):

my_corpus = CategorizedPlaintextCorpusReader('C:\\rss_feeds', r'.*/.*', cat_pattern=r'(.*)/.*',encoding='iso-8859-1')
print len(my_corpus.categories())
myfreq_dist = make_training_data(my_corpus)

但它只将结果更改为:

<FreqDist: u'\x92': 494, u'\x93': 300, u'\x97': 159, u',\x94': 134, u'company': 124, u'.\x94': 88, u'app': 84, u'Twitter': 82, u'people': 76, u'time': 73, ...>

python代码文件编码设置:

# -*- coding: iso-8859-1 -*-

为了完整起见,我使用以下代码将语料库阅读器操作到训练数据中:

def make_training_data(rdr):
    all_freq_dist = []
    #take union of all stopwords and punctuation marks
    punctuation = set(['.', '?', '!', ',', '$', ':', ';', '(',')','-',"`",'\'','"','>>','|','."',',"'])
    full_stop_set = set(nltk.corpus.stopwords.words('english')) | punctuation
    for c in rdr.categories():
        all_category_words = []
        for f in rdr.fileids(c):
            #try to remove stop words and punctuation
            filtered_file_words = [w for w in rdr.words(fileids=[f]) if not w.lower() in full_stop_set]
            #add the words from each file to the list of words for the category
            all_category_words = all_category_words + filtered_file_words
        list_cat_fd = FreqDist(all_category_words), c
        print list_cat_fd
        all_freq_dist.append(list_cat_fd)
    return all_freq_dist

当我在 Notepad++ 中打开文件本身时,它说它们是用 ANSI 编码的。

理想情况下,我想在生成频率分布之前从单词列表中删除特殊字符和标点符号。任何帮助将不胜感激。

4

1 回答 1

1

目前最简单的解决方案似乎是在生成频率分布之前将另一组字符(unicode_chars)添加到要消除的句点集中:

punctuation = set(['.', '?', '!', ',', '$', ':', ';', '(',')','-',"`",'\'','"','>>','|','."',',"'])
other_words = set([line.strip() for line in codecs.open('stopwords.txt',encoding='utf8')])
unicode_chars = set([u',\u201d',u'\u2019',u'\u2014',u'\u201c',u'.\u201d',u'\ufffd', u',\ufffd', u'.\ufffd'])
full_stop_set = set(nltk.corpus.stopwords.words('english')) | punctuation | other_words | unicode_chars

然后像以前一样在循环中:

filtered_file_words = [w for w in rdr.words(fileids=[f]) if not w.lower() in full_stop_set]

它可能不是最漂亮的,但它使奇怪的字符不被考虑在频率分布中。

于 2013-09-27T05:20:07.047 回答