任务描述
本关任务:读取停用词文件‘stop_words.txt’,对分词后的训练集和测试集文本去掉停用词及数值,并对分词后的整合。
相关知识
为了完成本关任务,你需要掌握:1.加载停用词;2.明确停用词的定义以及用法;3整合分词后的文本数据。
去停用词
停用词是指在信息检索中,为节省存储空间和提高搜索效率,在处理自然语言数据(或文本)之前或之后会自动过滤掉某些字或词,这些字或词即被称为Stop Words(停用词),分词之后有很多无用字符、或一些助词包括语气助词、副词、介词、连接词等,通常自身 并无明确的意义,只有将其放入一个完整的句子中才有一定作用,如常见的“的”、“在”之类等等,这些都需去掉。 示例如下:
#定义停用词的函数
def rm_stop_words(word_list):
stop_word=stl('stop_words.txt')
for i in range(word_list.__len__())[::-1]:
if word_list[i] in stop_word:
word_list.pop(i)
elif word_list[i].isdigit():#去数值
word_list.pop(i)
return word_list
整合分词后的数据
对每条标题,变成字符串,词之间用空格分开,即是整合后的结果。
trainX_txt=[]#整合后的训练数据
testX_txt=[]#整合后的测试数据
for i in range(len(r0)):
t=rm_stop_words(r0[i])
text=str()
for k in range(len(t)-1):
text=text+t[k]+ ' '
text=text+t[len(t)-1]
trainX_txt.append(text)
for i in range(len(r2)):
t=rm_stop_words(r2[i])
text=str()
for k in range(len(t)-1):
text=text+t[k]+ ' '
text=text+t[len(t)-1]
testX_txt.append(text)
编程要求
根据提示,在右侧编辑器补充代码,利用这些停用词,对文本数据清理。
测试说明
平台会对你编写的代码进行测试:
开始你的任务吧,祝你成功!
# -*- coding: utf-8 -*-
#读取停用词文件“stop_words.txt”,该文件为单列无表头的文件
#对上一关获得的分词后的训练集trainX_txt和测试集testX_txt,
#去掉停用词和数值,同时对每条标题(词列表),变成字符串(词之间用空格分开),
# 最后返回结果,同时也返回上一关的Y值(r[1])
#定义停用词的函数
def rm_stop_words(word_list):
stop_word=open('stop_words.txt', 'r').read().splitlines()
for i in range(len(word_list))[::-1]:
if word_list[i] in stop_word:
word_list.pop(i)
elif word_list[i].isdigit():#去数值
word_list.pop(i)
return word_list
def return_values():
import step10_1
r=step10_1.return_values()
trainX_txt=[]#整合后的训练数据
testX_txt=[]#整合后的测试数据
for i in range(len(r[0])):
t=rm_stop_words(r[0][i])
text=' '.join(t)
trainX_txt.append(text)
for i in range(len(r[2])):
t=rm_stop_words(r[2][i])
text=' '.join(t)
testX_txt.append(text)
return (trainX_txt,r[1],testX_txt)