一 过滤文本
去除停用词典和错词检错都可以用词典的形式完成,以停用词为例,我使用的应该是知网提供的中文停用词典。测试的数据集是小学生数学题。
print(text) # 打印未去除停用词前版本
with open(r"C:\Users\BF\Desktop\NLTK\stopwords.txt","r",encoding='utf-8') as stopfile: # 读取停用词,用utf-8的编码格式
txt = stopfile.readlines() # 一次性将所有的词按行读进来
stopword = set(word.strip('\n') for word in txt) # 去除每个词后的换行符放入tuple中
removetext = [word for word in text if word not in stopword] # 去除停用词
print(removetext)
停用词的下载链接
https://pan.baidu.com/s/1aGoVyl-NkBXwQ9nEbvisyQ
当然如果你自己的中文的错别字词典可以用同样的方式使用它,这里我用的是书本上英文文本的例子,找出文本中罕见的或者拼写错误的词汇表。这里有一个小技巧,如果你比较的是两个元祖,可以用自带的方法求两个元祖的交集,差集,并集。
def unusual_words(text):
text_vocab = set(w.lower() for w in text if w.isalpha()) # 读取带处理的文本
english_vocab = set(w.lower() for w in nltk.corpus.words.words()) # 读取nltk自带的过滤文本
unusual = text_vocab.difference(english_vocab)
return unusual
unusual_words(nltk.corpus.nps_chat.words())
二 过滤文本
发音词典,是为了语音合成器而设计的。中文的发音词典我也没找到,所以这章不介绍(可以用来找押韵词,对写歌的人估计很有帮助)