-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtokenizer.py
3319 lines (2968 loc) · 126 KB
/
tokenizer.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Tokenizer for Icelandic text
Copyright (C) 2016-2024 Miðeind ehf.
Original author: Vilhjálmur Þorsteinsson
This software is licensed under the MIT License:
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The function tokenize() consumes a text string and
returns a generator of tokens. Each token is a
named tuple, having the form (kind, txt, val),
where kind is one of the constants specified in the
TOK class, txt is the original source text,
and val contains auxiliary information
depending on the token type (such as the meaning of
an abbreviation, or the day, month and year for dates).
"""
from typing import (
Any,
Callable,
Deque,
Iterable,
Iterator,
Mapping,
Match,
Optional,
Type,
TypeVar,
Union,
cast,
)
import datetime
import re
import unicodedata # type: ignore
from collections import deque
from .abbrev import Abbreviations
from .definitions import *
_T = TypeVar("_T", bound="Tok")
# Set of punctuation characters that are grouped into one
# normalized exclamation
EXCLAMATIONS = frozenset(("!", "?"))
# Global constants for readability
SPAN_START = 0
SPAN_END = 1
class Tok:
"""Information about a single token"""
def __init__(
self,
kind: int,
txt: Optional[str],
val: ValType,
original: Optional[str] = None,
origin_spans: Optional[list[int]] = None,
) -> None:
# Type of token
self.kind: int = kind
# Text of the token
self.txt: str = txt or ""
# Value of the token (e.g. if it is a date or currency)
self.val: ValType = val
# The full original source string behind this token.
# If this is None then we're not tracking origins.
self.original: Optional[str] = original
# origin_spans contains an integer for each character in 'txt'.
# Each such integer index maps the corresponding character
# (which may have substitutions) to its index in 'original'.
# This is required to preserve 'original' correctly when splitting.
self.origin_spans: Optional[list[int]] = origin_spans
@classmethod
def from_txt(cls: Type[_T], txt: str) -> _T:
"""Create a token from text"""
return cls(TOK.RAW, txt, None, txt, list(range(len(txt))))
@classmethod
def from_token(cls: Type[_T], t: "Tok") -> _T:
"""Create a new Tok instance by copying from a previously existing one"""
return cls(
t.kind,
t.txt,
t.val,
t.original,
None if t.origin_spans is None else t.origin_spans[:],
)
@property
def punctuation(self) -> str:
"""Return the punctuation symbol associated with the
token, if it is in fact a punctuation token"""
if self.kind != TOK.PUNCTUATION:
# This is not a punctuation token. In that case,
# we return the Unicode 'unrecognized character'
# code, which will not match any 'x in s' checks
# where s is a legitimate string or set.
return "\ufffd"
return cast(PunctuationTuple, self.val)[1]
@property
def number(self) -> float:
"""Return a float embedded in a Number or Year token"""
if self.kind == TOK.YEAR:
return float(cast(int, self.val))
if self.kind == TOK.NUMBER:
return cast(NumberTuple, self.val)[0]
raise ValueError("Expected NUMBER or YEAR token in Tok.number()")
@property
def integer(self) -> int:
"""Return an integer from a token, which is assumed
to be a Number or a Year token"""
if self.kind == TOK.YEAR:
return cast(int, self.val)
if self.kind == TOK.NUMBER:
return int(cast(NumberTuple, self.val)[0])
raise ValueError("Expected NUMBER or YEAR token in Tok.integer()")
@property
def ordinal(self) -> int:
"""Return an ordinal number from a token,
which is assumed to be a Number or an Ordinal token"""
if self.kind == TOK.ORDINAL:
return cast(int, self.val)
if self.kind == TOK.NUMBER:
return int(cast(NumberTuple, self.val)[0])
raise ValueError("Expected NUMBER or ORDINAL token in Tok.ordinal()")
@property
def has_meanings(self) -> bool:
"""Return True if this is a word token and has meanings,
i.e. associated BIN_Tuple instances"""
if self.kind != TOK.WORD:
return False
return bool(self.val)
@property
def meanings(self) -> BIN_TupleList:
"""Return the meanings of this token if it is a word,
otherwise return an empty list"""
if self.kind != TOK.WORD:
return []
return cast(BIN_TupleList, self.val) or []
@property
def person_names(self) -> PersonNameList:
"""Return the person names of this token if it denotes a PERSON,
otherwise return an empty list"""
if self.kind != TOK.PERSON:
return []
return cast(PersonNameList, self.val) or []
def split(self, pos: int) -> tuple["Tok", "Tok"]:
"""Split this token into two at 'pos'.
The first token returned will have 'pos'
characters and the second one will have the rest.
"""
# TODO: What happens if you split a token that has
# txt=="" and original!=""?
# TODO: What should we do with val?
l: Tok
r: Tok
if self.origin_spans is not None and self.original is not None:
if pos >= len(self.origin_spans):
l = Tok(
self.kind,
self.txt,
self.val,
self.original,
self.origin_spans,
)
r = Tok(self.kind, "", None, "", [])
else:
l = Tok(
self.kind,
self.txt[:pos],
self.val,
self.original[: self.origin_spans[pos]],
self.origin_spans[:pos],
)
r = Tok(
self.kind,
self.txt[pos:],
self.val,
self.original[self.origin_spans[pos] :],
[x - self.origin_spans[pos] for x in self.origin_spans[pos:]],
)
else:
l = Tok(self.kind, self.txt[:pos], self.val)
r = Tok(self.kind, self.txt[pos:], self.val)
return l, r
def substitute(self, span: tuple[int, int], new: str) -> None:
"""Substitute a span with a single or empty character 'new'."""
self.txt = self.txt[: span[0]] + new + self.txt[span[1] :]
if self.origin_spans is not None:
# Remove origin entries that correspond to characters that are gone.
self.origin_spans = (
self.origin_spans[: span[0] + len(new)] + self.origin_spans[span[1] :]
)
def substitute_longer(self, span: tuple[int, int], new: str) -> None:
"""Substitute a span with a potentially longer string"""
# This tracks origin differently from the regular
# substitution function.
# Due to the inobviousness of how to assign origin to
# the new string we simply make it have an empty origin.
# This will probably cause some weirdness if this string
# later gets split or substituted but that should not
# happen in the current implementation.
self.txt = self.txt[: span[0]] + new + self.txt[span[1] :]
if self.origin_spans is not None and self.original is not None:
head = self.origin_spans[: span[0]]
tail = self.origin_spans[span[1] :]
# The origin span of the new stuff will be of length 0 since we can't
# proprely attribute it to individual characters in the original string.
if len(tail) == 0:
# We're replacing the end of the string
# Can't pick the next element after the removed string since it doesn't exist
# Use the length instead
new_origin = len(self.original)
else:
new_origin = self.origin_spans[span[1]]
self.origin_spans = head + [new_origin] * len(new) + tail
def substitute_all(self, old_str: str, new_char: str) -> None:
"""Substitute all occurrences of 'old_str' with 'new_char'.
The new character may be empty.
"""
# NOTE: This implementation is worst-case-quadratic in the
# length of the token text.
# Fortunately tokens are almost always (?) short so
# this is an acceptable tradeoff for a simple implementation.
# TODO: Support arbitrary length substitutions?
# What does that do to origin tracking?
assert len(new_char) <= 1, f"'new_char' ({new_char}) was too long."
while True:
i = self.txt.find(old_str)
if i == -1:
# No occurences of 'old_str' remain
break
self.substitute((i, i + len(old_str)), new_char)
def concatenate(
self,
other: "Tok",
*,
separator: str = "",
metadata_from_other: bool = False,
) -> "Tok":
"""Return a new token that consists of self with other
concatenated to the end.
A separator can optionally be supplied.
The new token will have metadata (kind and val)
from self unless 'metadata_from_other' is True.
"""
new_kind = self.kind if not metadata_from_other else other.kind
new_val = self.val if not metadata_from_other else other.val
self_txt = self.txt or ""
other_txt = other.txt or ""
new_txt = self_txt + separator + other_txt
self_original = self.original or ""
other_original = other.original or ""
new_original = self_original + other_original
self_origin_spans = self.origin_spans or []
other_origin_spans = other.origin_spans or []
separator_origin_spans: list[int] = (
[len(self_original)] * len(separator) if len(other_origin_spans) > 0 else []
)
new_origin_spans = (
self_origin_spans
+ separator_origin_spans
+ [i + len(self_original) for i in other_origin_spans]
)
return Tok(new_kind, new_txt, new_val, new_original, new_origin_spans)
@property
def as_tuple(self) -> tuple[Any, ...]:
"""Return the contents of this token as a generic tuple,
suitable e.g. for serialization"""
return (self.kind, self.txt, self.val)
def __getitem__(self, i: int) -> Union[int, str, ValType]:
"""Backwards compatibility for when Tok was a namedtuple."""
if i == 0:
return self.kind
elif i == 1:
return self.txt
elif i == 2:
return self.val
else:
raise IndexError("Tok can only be indexed by 0, 1 or 2")
def equal(self, other: "Tok") -> bool:
"""Equality of content between two tokens, i.e. ignoring the
'original' and 'origin_spans' attributes"""
return (
self.kind == other.kind and self.txt == other.txt and self.val == other.val
)
def __eq__(self, o: Any) -> bool:
"""Full equality between two Tok instances"""
if not isinstance(o, Tok):
return False
return (
self.kind == o.kind
and self.txt == o.txt
and self.val == o.val
and self.original == o.original
and self.origin_spans == o.origin_spans
)
def __repr__(self) -> str:
def quoted_string_repr(obj: Any) -> str:
if isinstance(obj, str):
return f'"{obj}"'
else:
return str(obj)
return (
f"Tok({self.kind}, {quoted_string_repr(self.txt)}, "
f"{self.val}, {quoted_string_repr(self.original)}, {self.origin_spans})"
)
class TOK:
"""
The TOK class contains constants that define token types and
constructors for creating token instances.
Each of the various constructors can accept as first parameter either
a string or a Tok object.
The string version is the old one (from versions 2 and earlier).
These take in a string and sometimes value and return a token with
that string and value.
This should be preserved while there are downstream users that depend on
this behavior. The tokenizer does not use this internally.
The Tok version of the constructors isn't really a constructor but rather
a converter. It takes in a token and returns a token with the given type
and value but preserves other attributes, in particular origin tracking.
Note that the current version modifies the input and returns it again.
This particular detail should not be depended on (assume the input is eaten
and something new is returned).
If, at some point, we can be reasonably certain that downstream users are
not using the string version any more we should consider removing it.
"""
# Token types
# Raw minimally processed token
RAW = -1
# Punctuation
PUNCTUATION = 1
# Time hh:mm:ss
TIME = 2
# Date yyyy-mm-dd
DATE = 3
# Year, four digits
YEAR = 4
# Number, integer or real
NUMBER = 5
# Word, which may contain hyphens and apostrophes
WORD = 6
# Telephone number: 7 digits, eventually preceded by country code
TELNO = 7
# Percentage (number followed by percent or promille sign)
PERCENT = 8
# A Uniform Resource Locator (URL): https://example.com/path?p=100
URL = 9
# An ordinal number, eventually using Roman numerals (1., XVII.)
ORDINAL = 10
# A timestamp (not emitted by Tokenizer)
TIMESTAMP = 11
# A currency sign or code
CURRENCY = 12
# An amount, i.e. a quantity with a currency code
AMOUNT = 13
# Person name (not used by Tokenizer)
PERSON = 14
# E-mail address (somebody@somewhere.com)
EMAIL = 15
# Entity name (not used by Tokenizer)
ENTITY = 16
# Unknown token type
UNKNOWN = 17
# Absolute date
DATEABS = 18
# Relative date
DATEREL = 19
# Absolute time stamp, yyyy-mm-dd hh:mm:ss
TIMESTAMPABS = 20
# Relative time stamp, yyyy-mm-dd hh:mm:ss
# where at least of yyyy, mm or dd is missing
TIMESTAMPREL = 21
# A measured quantity with its unit (220V, 0.5 km)
MEASUREMENT = 22
# Number followed by letter (a-z), often seen in addresses (Skógarstígur 4B)
NUMWLETTER = 23
# Internet domain name (an.example.com)
DOMAIN = 24
# Hash tag (#metoo)
HASHTAG = 25
# Chemical compound ('H2SO4')
MOLECULE = 26
# Social security number ('kennitala')
SSN = 27
# Social media user name ('@username_123')
USERNAME = 28
# Serial number ('394-8362')
SERIALNUMBER = 29
# Company name ('Google Inc.')
COMPANY = 30
# Sentinel value to for metatokens.
# Metatokens are tokens that are not directly based on characters in the text.
# Users can compare a token's kind with META_BEGIN to distinguish between
# metatokens and other tokens.
# Regular token kinds have a value less than META_BEGIN and
# metatokens have a kind greater than META_BEGIN.
META_BEGIN = 9999
# Sentence split token
S_SPLIT = 10000
# Paragraph begin
P_BEGIN = 10001
# Paragraph end
P_END = 10002
# Sentence begin
S_BEGIN = 11001
# Sentence end
S_END = 11002
# End sentinel
X_END = 12001
END = frozenset((P_END, S_END, X_END, S_SPLIT))
BEGIN = frozenset((P_BEGIN, S_BEGIN))
TEXT = frozenset((WORD, PERSON, ENTITY, MOLECULE, COMPANY))
TEXT_EXCL_PERSON = frozenset((WORD, ENTITY, MOLECULE, COMPANY))
# Token descriptive names
descr: Mapping[int, str] = {
PUNCTUATION: "PUNCTUATION",
TIME: "TIME",
TIMESTAMP: "TIMESTAMP",
TIMESTAMPABS: "TIMESTAMPABS",
TIMESTAMPREL: "TIMESTAMPREL",
DATE: "DATE",
DATEABS: "DATEABS",
DATEREL: "DATEREL",
YEAR: "YEAR",
NUMBER: "NUMBER",
NUMWLETTER: "NUMWLETTER",
CURRENCY: "CURRENCY",
AMOUNT: "AMOUNT",
MEASUREMENT: "MEASUREMENT",
PERSON: "PERSON",
WORD: "WORD",
UNKNOWN: "UNKNOWN",
TELNO: "TELNO",
PERCENT: "PERCENT",
URL: "URL",
DOMAIN: "DOMAIN",
HASHTAG: "HASHTAG",
EMAIL: "EMAIL",
ORDINAL: "ORDINAL",
ENTITY: "ENTITY",
MOLECULE: "MOLECULE",
SSN: "SSN",
USERNAME: "USERNAME",
SERIALNUMBER: "SERIALNUMBER",
COMPANY: "COMPANY",
S_SPLIT: "SPLIT SENT",
P_BEGIN: "BEGIN PARA",
P_END: "END PARA",
S_BEGIN: "BEGIN SENT",
S_END: "END SENT",
}
# Token constructors
@staticmethod
def Punctuation(t: Union[Tok, str], normalized: Optional[str] = None) -> Tok:
tp = TP_CENTER # Default punctuation type
if normalized is None:
if isinstance(t, str):
normalized = t
else:
normalized = t.txt
if normalized and len(normalized) == 1:
if normalized in LEFT_PUNCTUATION:
tp = TP_LEFT
elif normalized in RIGHT_PUNCTUATION:
tp = TP_RIGHT
elif normalized in NONE_PUNCTUATION:
tp = TP_NONE
if isinstance(t, str):
return Tok(TOK.PUNCTUATION, t, (tp, normalized))
t.kind = TOK.PUNCTUATION
t.val = (tp, normalized)
return t
@staticmethod
def Time(t: Union[Tok, str], h: int, m: int, s: int) -> Tok:
if isinstance(t, str):
return Tok(TOK.TIME, t, (h, m, s))
t.kind = TOK.TIME
t.val = (h, m, s)
return t
@staticmethod
def Date(t: Union[Tok, str], y: int, m: int, d: int) -> Tok:
if isinstance(t, str):
return Tok(TOK.DATE, t, (y, m, d))
t.kind = TOK.DATE
t.val = (y, m, d)
return t
@staticmethod
def Dateabs(t: Union[Tok, str], y: int, m: int, d: int) -> Tok:
if isinstance(t, str):
return Tok(TOK.DATEABS, t, (y, m, d))
t.kind = TOK.DATEABS
t.val = (y, m, d)
return t
@staticmethod
def Daterel(t: Union[Tok, str], y: int, m: int, d: int) -> Tok:
if isinstance(t, str):
return Tok(TOK.DATEREL, t, (y, m, d))
t.kind = TOK.DATEREL
t.val = (y, m, d)
return t
@staticmethod
def Timestamp(
t: Union[Tok, str], y: int, mo: int, d: int, h: int, m: int, s: int
) -> Tok:
if isinstance(t, str):
return Tok(TOK.TIMESTAMP, t, (y, mo, d, h, m, s))
t.kind = TOK.TIMESTAMP
t.val = (y, mo, d, h, m, s)
return t
@staticmethod
def Timestampabs(
t: Union[Tok, str], y: int, mo: int, d: int, h: int, m: int, s: int
) -> Tok:
if isinstance(t, str):
return Tok(TOK.TIMESTAMPABS, t, (y, mo, d, h, m, s))
t.kind = TOK.TIMESTAMPABS
t.val = (y, mo, d, h, m, s)
return t
@staticmethod
def Timestamprel(
t: Union[Tok, str], y: int, mo: int, d: int, h: int, m: int, s: int
) -> Tok:
if isinstance(t, str):
return Tok(TOK.TIMESTAMPREL, t, (y, mo, d, h, m, s))
t.kind = TOK.TIMESTAMPREL
t.val = (y, mo, d, h, m, s)
return t
@staticmethod
def Year(t: Union[Tok, str], n: int) -> Tok:
if isinstance(t, str):
return Tok(TOK.YEAR, t, n)
t.kind = TOK.YEAR
t.val = n
return t
@staticmethod
def Telno(t: Union[Tok, str], telno: str, cc: str = "354") -> Tok:
# The t parameter is the original token text,
# while telno has the standard form 'DDD-DDDD' (with hyphen)
# cc is the country code
if isinstance(t, str):
return Tok(TOK.TELNO, t, (telno, cc))
t.kind = TOK.TELNO
t.val = (telno, cc)
return t
@staticmethod
def Email(t: Union[Tok, str]) -> Tok:
if isinstance(t, str):
return Tok(TOK.EMAIL, t, None)
t.kind = TOK.EMAIL
t.val = None
return t
@staticmethod
def Number(
t: Union[Tok, str],
n: float,
cases: Optional[list[str]] = None,
genders: Optional[list[str]] = None,
) -> Tok:
# The cases parameter is a list of possible cases for this number
# (if it was originally stated in words)
if isinstance(t, str):
return Tok(TOK.NUMBER, t, (n, cases, genders))
t.kind = TOK.NUMBER
t.val = (n, cases, genders)
return t
@staticmethod
def NumberWithLetter(t: Union[Tok, str], n: int, c: str) -> Tok:
if isinstance(t, str):
return Tok(TOK.NUMWLETTER, t, (n, c))
t.kind = TOK.NUMWLETTER
t.val = (n, c)
return t
@staticmethod
def Currency(
t: Union[Tok, str],
iso: str,
cases: Optional[list[str]] = None,
genders: Optional[list[str]] = None,
) -> Tok:
# The cases parameter is a list of possible cases for this currency name
# (if it was originally stated in words, i.e. not abbreviated)
if isinstance(t, str):
return Tok(TOK.CURRENCY, t, (iso, cases, genders))
t.kind = TOK.CURRENCY
t.val = (iso, cases, genders)
return t
@staticmethod
def Amount(
t: Union[Tok, str],
iso: str,
n: float,
cases: Optional[list[str]] = None,
genders: Optional[list[str]] = None,
) -> Tok:
# The cases parameter is a list of possible cases for this amount
# (if it was originally stated in words)
if isinstance(t, str):
return Tok(TOK.AMOUNT, t, (n, iso, cases, genders))
t.kind = TOK.AMOUNT
t.val = (n, iso, cases, genders)
return t
@staticmethod
def Percent(
t: Union[Tok, str],
n: float,
cases: Optional[list[str]] = None,
genders: Optional[list[str]] = None,
) -> Tok:
if isinstance(t, str):
return Tok(TOK.PERCENT, t, (n, cases, genders))
t.kind = TOK.PERCENT
t.val = (n, cases, genders)
return t
@staticmethod
def Ordinal(t: Union[Tok, str], n: int) -> Tok:
if isinstance(t, str):
return Tok(TOK.ORDINAL, t, n)
t.kind = TOK.ORDINAL
t.val = n
return t
@staticmethod
def Url(t: Union[Tok, str]) -> Tok:
if isinstance(t, str):
return Tok(TOK.URL, t, None)
t.kind = TOK.URL
t.val = None
return t
@staticmethod
def Domain(t: Union[Tok, str]) -> Tok:
if isinstance(t, str):
return Tok(TOK.DOMAIN, t, None)
t.kind = TOK.DOMAIN
t.val = None
return t
@staticmethod
def Hashtag(t: Union[Tok, str]) -> Tok:
if isinstance(t, str):
return Tok(TOK.HASHTAG, t, None)
t.kind = TOK.HASHTAG
t.val = None
return t
@staticmethod
def Ssn(t: Union[Tok, str]) -> Tok:
if isinstance(t, str):
return Tok(TOK.SSN, t, None)
t.kind = TOK.SSN
t.val = None
return t
@staticmethod
def Molecule(t: Union[Tok, str]) -> Tok:
if isinstance(t, str):
return Tok(TOK.MOLECULE, t, None)
t.kind = TOK.MOLECULE
t.val = None
return t
@staticmethod
def Username(t: Union[Tok, str], username: str) -> Tok:
if isinstance(t, str):
return Tok(TOK.USERNAME, t, username)
t.kind = TOK.USERNAME
t.val = username
return t
@staticmethod
def SerialNumber(t: Union[Tok, str]) -> Tok:
if isinstance(t, str):
return Tok(TOK.SERIALNUMBER, t, None)
t.kind = TOK.SERIALNUMBER
t.val = None
return t
@staticmethod
def Measurement(t: Union[Tok, str], unit: str, val: float) -> Tok:
if isinstance(t, str):
return Tok(TOK.MEASUREMENT, t, (unit, val))
t.kind = TOK.MEASUREMENT
t.val = (unit, val)
return t
@staticmethod
def Word(t: Union[Tok, str], m: Optional[BIN_TupleList] = None) -> Tok:
# The m parameter is intended for a list of BIN_Tuple instances
# fetched from the BÍN database, in 'SHsnid' format
if isinstance(t, str):
return Tok(TOK.WORD, t, m)
t.kind = TOK.WORD
t.val = m
return t
@staticmethod
def Unknown(t: Union[Tok, str]) -> Tok:
if isinstance(t, str):
return Tok(TOK.UNKNOWN, t, None)
t.kind = TOK.UNKNOWN
t.val = None
return t
@staticmethod
def Person(t: Union[Tok, str], m: Optional[PersonNameList] = None) -> Tok:
# The m parameter is intended for a list of PersonName tuples:
# (name, gender, case)
if isinstance(t, str):
return Tok(TOK.PERSON, t, m)
t.kind = TOK.PERSON
t.val = m
return t
@staticmethod
def Entity(t: Union[Tok, str]) -> Tok:
if isinstance(t, str):
return Tok(TOK.ENTITY, t, None)
t.kind = TOK.ENTITY
t.val = None
return t
@staticmethod
def Company(t: Union[Tok, str]) -> Tok:
if isinstance(t, str):
return Tok(TOK.COMPANY, t, None)
t.kind = TOK.COMPANY
t.val = None
return t
@staticmethod
def Begin_Paragraph() -> Tok:
"""Return a special paragraph begin marker token"""
marker = Tok(TOK.P_BEGIN, "[[", None, "[[", list(range(2)))
marker.substitute((0, 2), "")
return marker
@staticmethod
def End_Paragraph() -> Tok:
"""Return a special paragraph end marker token"""
marker = Tok(TOK.P_END, "]]", None, "]]", list(range(2)))
marker.substitute((0, 2), "")
return marker
@staticmethod
def Begin_Sentence(
t: Optional[Tok] = None,
num_parses: int = 0,
err_index: Optional[int] = None,
) -> Tok:
if t is None:
return Tok(TOK.S_BEGIN, None, (num_parses, err_index))
t.kind = TOK.S_BEGIN
t.val = (num_parses, err_index)
return t
@staticmethod
def End_Sentence(t: Optional[Tok] = None) -> Tok:
if t is None:
return Tok(TOK.S_END, None, None)
t.kind = TOK.S_END
t.val = None
return t
@staticmethod
def End_Sentinel(t: Optional[Tok] = None) -> Tok:
if t is None:
return Tok(TOK.X_END, None, None)
t.kind = TOK.X_END
t.val = None
return t
@staticmethod
def Split_Sentence(t: Optional[Tok] = None) -> Tok:
if t is None:
return Tok(TOK.S_SPLIT, None, None)
t.kind = TOK.S_SPLIT
t.val = None
return t
class TokenStream:
"""Wrapper for token iterator allowing lookahead."""
def __init__(self, token_it: Iterator[Tok], *, lookahead_size: int = 2):
"""Initialize from token iterator."""
self._it: Iterator[Tok] = token_it
if lookahead_size <= 0:
lookahead_size = 1
self._lookahead: Deque[Tok] = deque(maxlen=lookahead_size)
self._max_lookahead: int = lookahead_size
def __next__(self) -> Tok:
if self._lookahead:
return self._lookahead.popleft()
return next(self._it)
def __iter__(self):
return self
def __getitem__(self, i: int) -> Optional[Tok]:
if 0 <= i < self._max_lookahead:
l = len(self._lookahead)
try:
while l <= i:
# Extend deque to lookahead
self._lookahead.append(next(self._it))
l += 1
return self._lookahead[i]
except StopIteration:
pass
return None
def txt(self, i: int = 0) -> Optional[str]:
"""Return token.txt for token at index i."""
t = self[i]
return t.txt if t else None
def kind(self, i: int = 0) -> Optional[int]:
"""Return token.kind for token at index i."""
t = self[i]
return t.kind if t else None
def punctuation(self, i: int = 0) -> Optional[str]:
"""Return token.punctuation for token at index i."""
t = self[i]
return t.punctuation if t else None
def number(self, i: int = 0) -> Optional[float]:
"""Return token.number for token at index i."""
t = self[i]
return t.number if t else None
def integer(self, i: int = 0) -> Optional[int]:
"""Return token.integer for token at index i."""
t = self[i]
return t.integer if t else None
def ordinal(self, i: int = 0) -> Optional[int]:
"""Return token.ordinal for token at index i."""
t = self[i]
return t.ordinal if t else None
def has_meanings(self, i: int = 0) -> Optional[bool]:
"""Return token.has_meanings for token at index i."""
t = self[i]
return t.has_meanings if t else None
def meanings(self, i: int = 0) -> Optional[BIN_TupleList]:
"""Return token.meanings for token at index i."""
t = self[i]
return t.meanings if t else None
def person_names(self, i: int = 0) -> Optional[PersonNameList]:
"""Return token.person_names for token at index i."""
t = self[i]
return t.person_names if t else None
def as_tuple(self, i: int = 0) -> Optional[tuple[Any, ...]]:
"""Return token.as_tuple for token at index i."""
t = self[i]
return t.as_tuple if t else None
def could_be_end_of_sentence(self, i: int = 0, *args: Any) -> bool:
"""Wrapper to safely check if token at index i could be end of sentence."""
t = self[i]
return could_be_end_of_sentence(t, *args) if t else False
def normalized_text(token: Tok) -> str:
"""Returns token text after normalizing punctuation"""
return (
cast(tuple[int, str], token.val)[1]
if token.kind == TOK.PUNCTUATION
else token.txt
)
def text_from_tokens(tokens: Iterable[Tok]) -> str:
"""Return text from a list of tokens, without normalization"""
return " ".join(t.txt for t in tokens if t.txt)
def normalized_text_from_tokens(tokens: Iterable[Tok]) -> str:
"""Return text from a list of tokens, with normalization"""
return " ".join(filter(None, map(normalized_text, tokens)))
def is_valid_date(y: int, m: int, d: int) -> bool:
"""Returns True if y, m, d is a valid date"""
if (1776 <= y <= 2100) and (1 <= m <= 12) and (1 <= d <= DAYS_IN_MONTH[m]):
try:
datetime.datetime(year=y, month=m, day=d)
return True
except ValueError:
pass
return False
def parse_digits(tok: Tok, convert_numbers: bool) -> tuple[Tok, Tok]:
"""Parse a raw token starting with a digit"""
w = tok.txt
s: Optional[Match[str]] = re.match(r"\d{1,2}:\d\d:\d\d,\d\d(?!\d)", w)
g: str
n: str
if s:
# Looks like a 24-hour clock with milliseconds, H:M:S:MS