Upload aztext/tokenize.py with huggingface_hub
Browse files- aztext/tokenize.py +49 -0
aztext/tokenize.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Simple, robust word and sentence tokenizers for Azerbaijani.
|
| 2 |
+
|
| 3 |
+
* :func:`word_tokenize` returns word tokens made of letters (ASCII +
|
| 4 |
+
Azerbaijani + combining marks) and digits, allowing internal apostrophes and
|
| 5 |
+
hyphens (e.g. ``Qur'an``, ``elmi-tədqiqat``). Punctuation is dropped.
|
| 6 |
+
* :func:`sent_tokenize` splits after sentence terminators ``. ! ? …`` while
|
| 7 |
+
keeping the terminator attached to its sentence.
|
| 8 |
+
|
| 9 |
+
Both use an explicit Azerbaijani letter class rather than ``\\w`` so behaviour
|
| 10 |
+
does not depend on the platform's Unicode word rules.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import re
|
| 14 |
+
|
| 15 |
+
from .alphabet import AZ_LETTERS
|
| 16 |
+
|
| 17 |
+
# Letter class: ASCII letters + Azerbaijani letters + combining marks.
|
| 18 |
+
_LETTER = "A-Za-z" + re.escape(AZ_LETTERS) + "̀-ͯ"
|
| 19 |
+
|
| 20 |
+
# A word: one or more letters/digits, optionally joined by a single internal
|
| 21 |
+
# apostrophe (straight or curly) or hyphen to more letters/digits.
|
| 22 |
+
_WORD_RE = re.compile(
|
| 23 |
+
r"[" + _LETTER + r"0-9]+(?:['’\-][" + _LETTER + r"0-9]+)*"
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
# Split on whitespace that follows a sentence terminator.
|
| 27 |
+
_SENT_SPLIT_RE = re.compile(r"(?<=[.!?…])\s+")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def word_tokenize(text: str) -> list:
|
| 31 |
+
"""Return the list of word tokens in ``text`` (punctuation removed)."""
|
| 32 |
+
if not text:
|
| 33 |
+
return []
|
| 34 |
+
return _WORD_RE.findall(text)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def sent_tokenize(text: str) -> list:
|
| 38 |
+
"""Split ``text`` into sentences.
|
| 39 |
+
|
| 40 |
+
Sentences are terminated by ``.``, ``!``, ``?`` or ``…`` (one or more) and
|
| 41 |
+
the terminator stays with its sentence. A trailing fragment without a
|
| 42 |
+
terminator is returned as its own sentence. Empty pieces are dropped.
|
| 43 |
+
"""
|
| 44 |
+
if not text:
|
| 45 |
+
return []
|
| 46 |
+
stripped = text.strip()
|
| 47 |
+
if not stripped:
|
| 48 |
+
return []
|
| 49 |
+
return [s for s in (p.strip() for p in _SENT_SPLIT_RE.split(stripped)) if s]
|