-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutil.py
48 lines (35 loc) · 1.29 KB
/
util.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
import math
import sys
import os
def get_window(prefix, mention, suffix, max_size):
if len(mention) >= max_size:
window = mention[:max_size]
return window, 0, len(window) - 1
leftover = max_size - len(mention)
leftover_half = int(math.ceil(leftover / 2))
if len(prefix) >= leftover_half:
prefix_len = leftover_half if len(suffix) >= leftover_half else \
leftover - len(suffix)
else:
prefix_len = len(prefix)
prefix = prefix[-prefix_len:] # Truncate head of prefix
window = prefix + mention + suffix
window = window[:max_size] # Truncate tail of suffix
mention_start_index = len(prefix)
mention_end_index = len(prefix) + len(mention) - 1
return window, mention_start_index, mention_end_index
class Logger(object):
def __init__(self, log_path, on=True):
self.log_path = log_path
self.on = on
if self.on:
while os.path.isfile(self.log_path):
self.log_path += '+'
def log(self, string, newline=True):
if self.on:
with open(self.log_path, 'a') as logf:
logf.write(string)
if newline: logf.write('\n')
sys.stdout.write(string)
if newline: sys.stdout.write('\n')
sys.stdout.flush()