Debian Codegraph @

importers/fd_import/tokenizer.py

raw
1 """Tokenizer for text-only dictionary formats.
2
3 To use this library, add your dictionary importer as a subdirectory to
4 importers/. Assuming you have an immporter in importers/foo, you would add the
5 following snippet to your foo.py to use this module:
6
7 from os.path import abspath, dirname
8 import sys
9
10 sys.path.append(dirname(dirname(abspath(sys.argv[0]))))
11
12 import tokenizer
13
14 For the usage, please see the functions and classes defined in this module."""
15
16 import enum
17 import inspect
18
19
20 class ChunkType(enum.Enum):
21 """The tokenizer parses individual chunks and emits tuples with type
22 information and chunk content. The first entry is the chunk type, as defined
23 by this enum."""
24 Word = 0
25 Paren = 1 # parenthesized expressions ()
26 Bracket = 2 # brackets []
27 Brace = 3 # "embraced" expressions: {}
28 Semicolon = 4 # delimiter, e.g. homonyms
29 Comma = 5 # word/definition boundary
30 VerticalBar = 6 # has to be surrounded by spaces, is a delimiter as e.g. comma
31 Slash = 7 # optional; example usage include abbreviations "/ETC/"
32
33 def __repr__(self):
34 return '<%s.%s>' % (self.__class__.__name__, self.name)
35
36 def space_before_slash(string, i):
37 """The tokenizer can recognize chunks enclosed by slashes. To avoid to many
38 false positives, only expressions with no space are supported, ATM. This
39 functions checks whether a space is found before the next slash."""
40 for ch in string[i+1:]: # skip first character, is the very slash
41 if ch.isspace():
42 return True
43 elif ch == '/':
44 return False
45 return True # end of string reached, is like a space
46
47
48 FRAMING = {'(': ChunkType.Paren, '[': ChunkType.Bracket, '{': ChunkType.Brace}
49 CLOSING = {')':'(', '}':'{', ']':'['}
50 def tokenize(source, parse_slash=False):
51 #pylint: disable=redefined-variable-type,too-many-branches
52 """Tokenize a line (of translations) into chunks, where each chunk is a tuple of (ChunkType,
53 content). This only works with either the headword or the translation part,
54 so instead of:
55
56 abc - a, b; c
57 It either parses "abc" or "a, b; c".
58
59 Chunk types with no value (as for instance Comma) return a tuple with None as
60 second element.
61
62 Parenthesis have precedence over commas and ;. So
63
64 a, b (c,;d)
65
66 will be tokenized as
67
68 [(Word, 'a'), (Comma, None), (Word, 'b'), (Paren, 'c,;d')]
69
70 The prefix ChunkType has been omitted for readibility reasons.
71 This precedence rule also means that nested structures are *not* recognized,
72 the outer wins. This won't work:
73
74 ([(blah)])
75
76 will result in
77
78 [(Paren, '[(blah'), (Word, '])')]
79 """
80 chunks = []
81 tmp_storage = [] # for unfinished chunks
82 def save_parsed_chunk(ctype):
83 """Save tmp_storage in chunks with the given type. This function is a short-hand."""
84 nonlocal chunks, tmp_storage
85 if not all(c.isspace() for c in tmp_storage):
86 chunks.append((ctype, ''.join(tmp_storage).strip()))
87 tmp_storage = []
88 state = ChunkType.Word # current state of parser (ChunkType)
89 prevchar = ''
90
91 is_new_word = lambda: prevchar == '' or prevchar.isspace()
92 for idx, ch in enumerate(source):
93 if state in FRAMING.values() or (parse_slash and state == ChunkType.Slash):
94 if ch in CLOSING and state == FRAMING[CLOSING[ch]]:
95 save_parsed_chunk(FRAMING[CLOSING[ch]])
96 state = ChunkType.Word
97 elif ch == '/' and state == ChunkType.Slash and parse_slash:
98 save_parsed_chunk(ChunkType.Slash)
99 state = ChunkType.Word
100 else: # within the brace/bracket/parethesis
101 tmp_storage.append(ch)
102
103 else: # ChunkType.Word
104 # separate a enclosed expression if preceded by whitespace /
105 # beginning of string; handle slash separately
106 if is_new_word() and (ch in FRAMING or (parse_slash and \
107 ch == '/' and not space_before_slash(source, idx))):
108 # above tests that / is followed by characters only, no spaces
109 # and hence no straying slashes are detected
110 if ch == '/' and parse_slash:
111 state = ChunkType.Slash
112 else:
113 state = FRAMING[ch]
114 if tmp_storage: # add word before, if any
115 save_parsed_chunk(ChunkType.Word)
116 # only recognize /foo/ if parse_slash and if space in front
117 elif ch == ',': # comma outside of parens, new word
118 if tmp_storage: # not empty
119 save_parsed_chunk(ChunkType.Word)
120 chunks.append((ChunkType.Comma, None))
121 elif ch == ';':
122 if tmp_storage: # not empty
123 save_parsed_chunk(ChunkType.Word)
124 chunks.append((ChunkType.Semicolon, None))
125 elif ch == '|' and (prevchar == '' or prevchar.isspace()): # space around?
126 if tmp_storage: # not empty
127 save_parsed_chunk(ChunkType.Word)
128 chunks.append((ChunkType.VerticalBar, None))
129
130 else:
131 tmp_storage.append(ch)
132 prevchar = ch
133 if tmp_storage:
134 save_parsed_chunk(ChunkType.Word)
135 return chunks
136
137
138
139 def split_list(mylist, delim):
140 """Split a list into chunks with the given delimiter. If a delimiter is a
141 function, it will get the list item as function and has to return true if a
142 split should occur. Returned is an iterator, yielding a chunk at a time.
143 Examples:
144
145 >>> list(split_list([1,2,3,2,4,5,2,2,10], 2))
146 [[1],[3],[4,5],[],10]]
147 >>> list(split_list([]))
148 []
149 >>> list(split_list([1,2,3,4], 20))
150 [[1,2,3,4]]"""
151 if not mylist:
152 return []
153 gathered = []
154 is_splitpoint = (delim if inspect.isfunction(delim)
155 else lambda e: e == delim)
156 for elem in mylist:
157 if is_splitpoint(elem):
158 yield gathered
159 gathered = []
160 else:
161 gathered.append(elem)
162 yield gathered
163