This repository was archived by the owner on Oct 8, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_preprocess.py
More file actions
89 lines (63 loc) · 2.74 KB
/
Copy pathdata_preprocess.py
File metadata and controls
89 lines (63 loc) · 2.74 KB
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
import json
import os
def class_identifier(path):
"""
Добавляет в ключ 'answers' для каждого элемента ключ - 'n_cluster' где отображает номер кластера, относительно других.
Также добавляет в ключ 'clusters' - количество кластеров.
Args:
path: путь json-файла
Return:
dict: Словарь в формате json с добавленными ключами.
"""
with open(path, encoding='utf-8-sig') as f:
json_file = json.load(f)
answers = json_file['answers']
clusters = {}
num_cluster = 0
for batch in answers:
if batch['cluster'] in clusters:
cl = clusters[batch['cluster']]
else:
clusters[batch['cluster']] = num_cluster
cl = num_cluster
num_cluster += 1
batch['n_cluster'] = cl
json_file['clusters'] = num_cluster
return json_file
def merge_duplicate_answers(json_data):
'''
Объединяет дублирующиеся ответы и суммирует их количество.
Args:
json_data type: dict[list[dict]]: Cловарь с ключом 'asnwers' и вложенными в нём списком словарей с ключами: 'answer' и 'count'.
Return:
list: Новый список словарей с уникальными записями 'answer' и их суммированными значениями 'count'.
'''
unique_answers = {}
for item in json_data['answers']:
answer = item['answer']
count = item['count']
if answer in unique_answers:
unique_answers[answer] += count
else:
unique_answers[answer] = count
answers = [{'answer': answer, 'count': count} for answer, count in unique_answers.items()]
return answers
# ТРЕНИРОВОЧНЫЕ ДАННЫЕ
output_file = r'data/train_data.json'
data = []
for file in os.scandir('data/labeled/'):
json_file = class_identifier(file.path)
data.append(json_file)
with open(output_file, encoding='utf-8-sig', mode='w') as f:
f.write(json.dumps(data, indent=4))
# ТЕСТОВЫЕ ДАННЫЕ
output_file = r'data/test_data.json'
data = []
for file in os.scandir('data/all/'):
with open(file, encoding='utf-8-sig') as f:
json_file = json.load(f)
json_file['answers'] = merge_duplicate_answers(json_file)
data.append(json_file)
data.append(json_file)
with open(output_file, encoding='utf-8-sig', mode='w') as f:
f.write(json.dumps(data, indent=4))