2013-09-26 29 views
0

我已經下載並清理了一組RSS源以用作用於測試分類的NLTK的語料庫。但是,當我運行頻率分佈許多頂級的結果似乎是特殊字符:使用NLTK處理Python中的字符編碼問題

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

我試圖在這個問題here建議正是如此初始化語料庫(指定編碼):

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 

當我在記事本中打開文件本身++它說它們是用ANSI編碼的。

理想情況下,我想在生成頻率分佈之前從單詞列表中刪除特殊字符和標點符號。任何幫助將不勝感激。

+0

它可能不是特殊字符,它可能是重音字符。請參閱http://stackoverflow.com/questions/3328995/how-to-remove-xe2-from-a-list – alvas

回答

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] 

它可能不是最漂亮的,但它保持在頻率分佈中考慮奇怪的字符。