-
Notifications
You must be signed in to change notification settings - Fork 0
/
wordnet-31-to-json.py
92 lines (70 loc) · 2.6 KB
/
wordnet-31-to-json.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2022 Jordi Mas i Hernandez <jmas@softcatala.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
import json
import os
import fnmatch
def find(directory, pattern):
filelist = []
for root, dirs, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
filename = os.path.join(root, basename)
filelist.append(filename)
filelist.sort()
return filelist
def load_json(filename):
try:
with open(filename, 'r') as fh:
entry = json.load(fh)
return entry
except:
print(f"Unable to load {filename}")
return None
def main():
print("Read individual jsons and produce a single json")
terms = []
output_folder = 'produced'
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for filename in find('downloaded/', '*.json'):
entry = load_json(filename)
if entry is None:
continue
sysnet30_id = os.path.basename(filename).replace('.json', '')
entry = entry[0]
term = {}
term['id'] = entry['id']
term['subject'] = entry['subject']
term['pos'] = entry['pos']
term['sysnet30_id'] = sysnet30_id
if 'cat' in entry['foreign']:
term['ca'] = entry['foreign']['cat']
terms.append(term)
with open(f'{output_folder}/terms.json', 'w') as outfile:
json.dump(terms, outfile, indent=4, ensure_ascii=False)
with open(f'{output_folder}/words.txt', 'w') as outfile:
for term in terms:
outfile.write(f"{term}\n")
with open(f'{output_folder}/synset_ids_31.txt', 'w') as outfile:
for term in terms:
outfile.write(f"{term['id']}\t{term['sysnet30_id']}\t{term['subject']}\t{term['pos']}\n")
print(f"Written {len(terms)}")
if __name__ == "__main__":
main()