reindex_sentences.py
2.77 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
90
91
92
import argparse
import os
def main():
args = parse_arguments()
if not args.input or not args.output:
print('Error: Input and output must be selected!')
copy_by_year(args.input, args.output)
def parse_arguments():
parser = argparse.ArgumentParser(description='Reindex sentences in conllup corpora.')
parser.add_argument('-o', '--output', help='output directory')
required_arguments = parser.add_argument_group('required arguments')
required_arguments.add_argument('-i', '--input', help='corpora root directory', required=True)
return parser.parse_args()
def copy_by_year(root_directory, out_corpora_directory):
for root, dirs, files in os.walk(root_directory):
for filename in files:
if filename.endswith('.conllup') or filename.endswith('.conllu'):
src = os.path.join(root, filename)
year = get_year(src)
year_path = os.path.join(out_corpora_directory, year)
os.makedirs(year_path, exist_ok=True)
dst = os.path.join(year_path, filename)
reindex_and_save(src, dst)
def get_year(filepath):
with open(filepath, 'r') as conllup_file:
for line in conllup_file:
line = line.strip()
if is_segment(line):
continue
elif is_metadata(line):
name, value = get_metadata(line)
if name == 'date':
return value.split('-')[0]
return 0
def is_segment(line):
if line and line[0].isdigit():
return True
return False
def is_metadata(line):
if line.startswith('#'):
return True
return False
def get_metadata(line):
name_value_pair = line.split('=', 1)
name = name_value_pair[0].lstrip('#').strip()
value = name_value_pair[1].strip()
return name, value
def reindex_and_save(src, dst):
cleaned_lines = []
paragraph_id = 0
sentence_id = 0
doc_id = os.path.basename(src).split('.')[0]
with open(src, 'r') as conllup_file:
for line in conllup_file:
line = line.strip()
if is_metadata(line):
name, value = get_metadata(line)
if name == 'newpar id':
sentence_id = 0
paragraph_id += 1
cleaned_lines.append(f'# newpar id = {doc_id}-p{paragraph_id}')
elif name == 'sent_id':
sentence_id += 1
cleaned_lines.append(f'# sent_id = {doc_id}-p{paragraph_id}s{sentence_id}')
else:
cleaned_lines.append(line)
else:
cleaned_lines.append(line)
with open(dst, 'w') as dst_file:
dst_file.write('\n'.join(cleaned_lines))
if __name__ == '__main__':
main()