Files
Liber-public/crates/liber-lang/src/token.rs
T

97 lines
3.3 KiB
Rust

//! Words by Unicode word boundaries (UAX #29), with the reader's UTF-16 offsets.
use serde::Serialize;
use unicode_segmentation::UnicodeSegmentation;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
Word,
/// Digits, or a Roman numeral of two or more letters (`XII`, `IV`): never a word to learn.
Number,
Punct,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Token {
pub text: String,
/// UTF-16 offsets into the text given to [`tokens`].
pub start: usize,
pub end: usize,
pub kind: Kind,
/// The first word of a sentence (after `.`, `!`, `?`, `…`, `:` before a capital, or the start).
pub sentence_start: bool,
}
impl Token {
pub fn capitalised(&self) -> bool {
self.text.chars().next().is_some_and(char::is_uppercase)
}
}
fn roman(s: &str) -> bool {
s.chars().count() >= 2 && s.chars().all(|c| "IVXLCDM".contains(c))
}
/// Every word, number and punctuation mark; whitespace is skipped. A word's apostrophes stay inside it (`don't`).
pub fn tokens(text: &str) -> Vec<Token> {
let mut out = Vec::new();
let mut utf16 = 0usize;
let mut sentence = true;
for (_, piece) in text.split_word_bound_indices() {
let len = piece.encode_utf16().count();
let start = utf16;
utf16 += len;
if piece.chars().all(char::is_whitespace) {
continue;
}
let kind = if piece.chars().any(char::is_alphabetic) {
if roman(piece) { Kind::Number } else { Kind::Word }
} else if piece.chars().any(|c| c.is_ascii_digit() || c.is_numeric()) {
Kind::Number
} else {
Kind::Punct
};
let starts = sentence && kind != Kind::Punct;
out.push(Token { text: piece.to_owned(), start, end: utf16, kind, sentence_start: starts });
match kind {
Kind::Punct if piece.chars().any(|c| matches!(c, '.' | '!' | '?' | '…' | '¿' | '¡')) => sentence = true,
Kind::Punct => {}
_ => sentence = false,
}
}
out
}
/// Sentences of a paragraph as `(start, end)` UTF-16 ranges, split after `.`, `!`, `?`, `…` (and closing quotes
/// after them). Abbreviations are not handled; the aligner tolerates the odd extra split.
pub fn sentences(text: &str) -> Vec<(usize, usize)> {
let toks = tokens(text);
let closer = |t: &Token| t.kind == Kind::Punct && t.text.chars().all(|c| "\"'”’»«)]".contains(c));
let mut out = Vec::new();
let mut begin: Option<usize> = None;
let mut end = 0;
let mut pending = false;
for (i, t) in toks.iter().enumerate() {
if begin.is_none() && t.kind != Kind::Punct {
begin = Some(t.start);
}
end = t.end;
let stop = t.kind == Kind::Punct && t.text.chars().any(|c| matches!(c, '.' | '!' | '?' | '…'));
if stop || (pending && closer(t)) {
if toks.get(i + 1).is_some_and(closer) {
pending = true;
} else if let Some(b) = begin.take() {
out.push((b, end));
pending = false;
}
} else if t.kind != Kind::Punct {
pending = false;
}
}
if let Some(b) = begin {
out.push((b, end));
}
out
}