使用NLTK处理Python中的字符编码问题

2024-09-28 20:59:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

<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 -*-

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

^{pr2}$

当我在记事本++中打开这些文件时,它说它们是用ANSI编码的。在

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


Tags: app编码mytwittercorpuspeoplecompany频率
1条回答
网友
1楼 · 发布于 2024-09-28 20:59:13

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

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

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

^{pr2}$

它可能不是最漂亮的,但它可以避免在频率分布中考虑到奇怪的特征。在

相关问题 更多 >