INPUT: file - (str) 数据文件的路径 OUTPUT: org_topics - (list) 原始话题标签列表 text - (list) 文本列表 words - (list) 单词列表
(file)
| 28 | |
| 29 | #定义加载数据的函数 |
| 30 | def load_data(file): |
| 31 | ''' |
| 32 | INPUT: |
| 33 | file - (str) 数据文件的路径 |
| 34 | |
| 35 | OUTPUT: |
| 36 | org_topics - (list) 原始话题标签列表 |
| 37 | text - (list) 文本列表 |
| 38 | words - (list) 单词列表 |
| 39 | |
| 40 | ''' |
| 41 | df = pd.read_csv(file) #读取文件 |
| 42 | org_topics = df['category'].unique().tolist() #保存文本原始的话题标签 |
| 43 | df.drop('category', axis=1, inplace=True) |
| 44 | n = df.shape[0] #n为文本数量 |
| 45 | text = [] |
| 46 | words = [] |
| 47 | for i in df['text'].values: |
| 48 | t = i.translate(str.maketrans('', '', string.punctuation)) #去除文本中的标点符号 |
| 49 | t = [j for j in t.split() if j not in stopwords.words('english')] #去除文本中的停止词 |
| 50 | t = [j for j in t if len(j) > 3] #长度小于等于3的单词大多是无意义的,直接去除 |
| 51 | text.append(t) #将处理后的文本保存到文本列表中 |
| 52 | words.extend(set(t)) #将文本中所包含的单词保存到单词列表中 |
| 53 | words = list(set(words)) #去除单词列表中的重复单词 |
| 54 | return org_topics, text, words |
| 55 | |
| 56 | |
| 57 | #定义构建单词-文本矩阵的函数,这里矩阵的每一项表示单词在文本中的出现频次,也可以用TF-IDF来表示 |