-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathread_files.py
325 lines (244 loc) · 10.1 KB
/
read_files.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import os
import re
import sys
import csv,random
csv.field_size_limit(500 * 1024 * 1024)
from config import config
import numpy as np
import string
def rm_tags(text):
re_tag = re.compile(r'<[^>]+>')
return re_tag.sub('', text)
def read_imdb_files(path, filetype):
"""
filetype: 'train' or 'test'
"""
all_texts = []
file_list = []
# path = r'../../data_set/aclImdb/'
pos_path = path + filetype + '/pos/'
for file in os.listdir(pos_path):
file_list.append(pos_path + file)
neg_path = path + filetype + '/neg/'
for file in os.listdir(neg_path):
file_list.append(neg_path + file)
for file_name in file_list:
with open(file_name, 'r') as f:
all_texts.append(rm_tags(" ".join(f.readlines())))
all_labels = []
for _ in range(12500):
all_labels.append([0, 1])
for _ in range(12500):
all_labels.append([1, 0])
data = list(zip(all_texts,all_labels))
random.shuffle(data)
all_texts, all_labels = zip(*data)
return all_texts, all_labels
def split_imdb_files(path):
print('Processing IMDB dataset')
train_texts, train_labels = read_imdb_files(path, 'train')
test_texts, test_labels = read_imdb_files(path, 'test')
return train_texts, train_labels, test_texts, test_labels
def read_fake_csv_files_backup(filetype):
texts = []
labels_index = [] # The index of label of all input sentences, which takes the values 1,2,3,4
doc_count = 0 # number of input sentences
path = r'../../data_set/fake/{}.csv'.format(filetype)
csv.field_size_limit(500 * 1024 * 1024)
csvfile = open(path, 'r')
flag = 0
for index,line in enumerate(csv.reader(csvfile, delimiter=',', quotechar='"')):
# print(index,'index',len(line),'len(line)')
# if index != 5200: continue
if flag == 0:
flag = 1
continue
if len(line) < 5: continue
content = line[3]
texts.append(content)
labels_index.append(line[-1])
doc_count += 1
# Start document processing
labels = []
for i in range(doc_count):
label_class = np.zeros(config.num_classes['fake'], dtype='float32')
label_class[int(labels_index[i]) - 1] = 1
labels.append(label_class)
return texts, labels, labels_index
def read_fake_csv_files(path, filetype):
texts = []
labels_index = [] # The index of label of all input sentences, which takes the values 1,2,3,4
doc_count = 0 # number of input sentences
# cwd = os.getcwd()
# print(cwd,'cwd')
path = path + '{}_tok.csv'.format(filetype)
csvfile = open(path, 'r')
content_lst = []
# w_path = r'./data_set/ag_news_csv/new_{}.csv'.format(filetype)
# w_csv_file = open(w_path, 'w')
# writer = csv.writer(w_csv_file,delimiter=',')
for line in csv.reader(csvfile, delimiter=',', quotechar='"'):
content_lst.append(line)
content = line[0]
texts.append(content)
labels_index.append(line[1])
doc_count += 1
# Start document processing
labels = []
for i in range(doc_count):
label_class = np.zeros(config.num_classes['fake'], dtype='float32')
label_class[int(labels_index[i]) - 1] = 1
labels.append(label_class)
# for line in content_lst:
# writer.writerow(line)
return texts, labels, labels_index
def split_fake_csv_files(path):
print("Processing Fake CSV dataset")
train_texts, train_labels, _ = read_fake_csv_files(path,'train')
# train_texts, test_texts, train_labels, test_labels = train_test_split(texts, labels, test_size=0.2)
test_texts, test_labels, _ = read_fake_csv_files(path, 'test')
return train_texts, train_labels, test_texts, test_labels
def read_mr_csv_files(path, file_name):
texts = []
labels_index = [] # The index of label of all input sentences, which takes the values 1,2,3,4
doc_count = 0 # number of input sentences
content = []
# file_name = r'../../data_set/mr/{}.txt'.format(file_name)
# path = '../../data_set/fake/{}_tok.csv'.format(filetype)
file_name = path + '{}.txt'.format(file_name)
with open(file_name, 'r', encoding='utf-8') as f:
# content += [line.strip().split() for line in f if line.strip()]
content = f.readlines()
for sentence in content:
labels_index.append(sentence[0])
sentence = sentence[2:].strip()
texts.append(sentence)
doc_count+=1
labels = []
for i in range(doc_count):
label_class = np.zeros(config.num_classes['mr'], dtype='float32')
label_class[int(labels_index[i])] = 1
labels.append(label_class)
return texts, labels, labels_index
def split_MR_test_files(data_path):
print("Processing MR Test CSV dataset")
train_texts, train_labels, _ = read_mr_csv_files(data_path,'train')
test_texts, test_labels, _ = read_mr_csv_files(data_path, 'test')
return train_texts, train_labels, test_texts, test_labels
def read_mnli_csv_files(path, file_name, model):
texts = []
labels_index = [] # The index of label of all input sentences, which takes the values 1,2,3,4
doc_count = 0 # number of input sentences
file_name = path + r'mnli_{}.txt'.format(file_name)
if model == 'bert':
labeldict = {"contradiction": 0,
"entailment": 1,
"neutral": 2}
else:
labeldict = {"entailment": 0,
"neutral": 1,
"contradiction": 2}
with open(file_name, 'r', encoding='utf-8') as f:
# content += [line.strip().split() for line in f if line.strip()]
content = f.readlines()
for sentence in content:
sentence_lst = sentence.strip().split('\t')
labels_index.append(labeldict[sentence_lst[0]])
sentence = (sentence_lst[1],sentence_lst[2])
texts.append(sentence)
doc_count += 1
labels = []
for i in range(doc_count):
label_class = np.zeros(len(labeldict), dtype='float32')
label_class[int(labels_index[i])] = 1
labels.append(label_class)
return texts, labels
def split_mnli_test_files(path, model):
'type 0 tokenzier, hownet type 1 can_save type 2 train'
print("Processing mnli_CSV dataset")
train_texts, train_labels = read_mnli_csv_files(path, 'train', model)
test_texts, test_labels = read_mnli_csv_files(path, 'test', model)
return train_texts, train_labels, test_texts, test_labels
def read_snli_test_csv_files(path, file_name, model):
# filepath = r'../../data_set/snli_1.0/snli_1.0_test.txt'
filepath = path + r'snli_1.0_{}.txt'.format(file_name)
if model == 'bert':
labeldict = {"contradiction": 0,
"entailment": 1,
"neutral": 2}
else:
labeldict = {"entailment": 0,
"neutral": 1,
"contradiction": 2}
with open(filepath, "r", encoding="utf8") as input_data:
# ids, premises, hypotheses, labels = [], [], [], []
texts, labels = [], []
# Translation tables to remove parentheses and punctuation from
# strings.
parentheses_table = str.maketrans({"(": None, ")": None})
punct_table = str.maketrans({key: " "
for key in string.punctuation})
# Ignore the headers on the first line of the file.
next(input_data)
for line in input_data:
line = line.strip().split("\t")
# Ignore sentences that have no gold label.
if line[0] == "-":
continue
premise = line[1]
hypothesis = line[2]
# Remove '(' and ')' from the premises and hypotheses.
premise = premise.translate(parentheses_table)
hypothesis = hypothesis.translate(parentheses_table)
premise = premise.translate(punct_table)
hypothesis = hypothesis.translate(punct_table)
texts.append((premise,hypothesis))
label_class = np.zeros(len(labeldict), dtype='float32')
label_class[int(labeldict[line[0]])] = 1
labels.append(label_class)
return texts, labels
def CleanStr(s):
s = re.sub(r'([-~【】!、。,?“”()().!?''""])', r' ', s) #
return s # 返回的是list
def split_snli_test_files(path, model):
print("Processing snli Test CSV dataset")
train_texts, train_labels= read_snli_test_csv_files(path, 'train', model)
test_texts, test_labels = read_snli_test_csv_files(path, 'test', model)
return train_texts, train_labels, test_texts, test_labels
#
def read_agnews_files(path, filetype):
texts = []
labels_index = [] # The index of label of all input sentences, which takes the values 1,2,3,4
doc_count = 0 # number of input sentences
# cwd = os.getcwd()
# print(cwd,'cwd')
path = path + '{}.csv'.format(filetype)
csvfile = open(path, 'r')
content_lst = []
# w_path = r'./data_set/ag_news_csv/new_{}.csv'.format(filetype)
# w_csv_file = open(w_path, 'w')
# writer = csv.writer(w_csv_file,delimiter=',')
for line in csv.reader(csvfile, delimiter=',', quotechar='"'):
content_lst.append(line)
content = line[1] + ". " + line[2]
texts.append(content)
labels_index.append(line[0])
doc_count += 1
# Start document processing
labels = []
for i in range(doc_count):
label_class = np.zeros(config.num_classes['agnews'], dtype='float32')
label_class[int(labels_index[i]) - 1] = 1
labels.append(label_class)
# for line in content_lst:
# writer.writerow(line)
return texts, labels, labels_index
def split_agnews_files(data_path):
print("Processing AG's News dataset")
train_texts, train_labels, _ = read_agnews_files(data_path,'train') # 120000
test_texts, test_labels, _ = read_agnews_files(data_path,'test') # 7600
return train_texts, train_labels, test_texts, test_labels
if __name__ == '__main__':
split_agnews_files()
# split_weibo_files()
# split_fake_test_files()