Unicode Text Segmentation for MoonBit
moon add moonbit-community/unicode-segmentationfor segment in @segmentation.word_segments("Hello, world! 42") {
// "Hello", ",", " ", "world", "!", " ", "42"
}
for word in @segmentation.words("Hello, world! 42") {
// "Hello", "world", "42"
}
for sentence in @segmentation.sentences("Hello! Next.") {
// "Hello! ", "Next."
}| Entry point | Cursor | Contents |
|---|---|---|
| word_segments(StringView) | WordSegments | All default UAX #29 word segments, including whitespace and punctuation. |
| words(StringView) | Words | Word segments containing at least one Unicode Alphabetic character or General_Category=Number character (Nd, Nl, or No). |
| sentences(StringView) | Sentences | All default UAX #29 sentence segments, retaining closing punctuation, trailing whitespace, and paragraph separators as specified by the rules. |
let graphemes = @segmentation.graphemes("ab c")
for grapheme in graphemes {
let opportunity = graphemes.line_break()
// "a" -> Prohibited, "b" -> Prohibited,
// " " -> Allowed, "c" -> Mandatory
}let breaks = @segmentation.line_breaks("Hello world!")
for segment in breaks {
let opportunity = breaks.opportunity()
// "Hello " -> Allowed, "world!" -> Mandatory
}moon test --target native segmentation tests/linebreak_tests tests/segmentation_teststype Graphemestest {
let graphemes = @segmentation.graphemes("ab c")
let kinds = []
for grapheme in graphemes {
kinds.push((grapheme.to_owned(), graphemes.line_break()))
}
debug_inspect(
kinds,
content=(
#|[
#| ("a", Prohibited),
#| ("b", Prohibited),
#| (" ", Allowed),
#| ("c", Mandatory),
#|]
),
)
}test {
let clusters = @segmentation.graphemes("e\u{301}x")
inspect(
clusters.next(),
content=(
#|é
),
)
inspect(
clusters.next(),
content=(
#|x
),
)
inspect(
clusters.next().is_empty(),
content=(
#|true
),
)
}type LineBreakstype Sentencestype WordSegmentstype Wordstest {
let clusters = []
for cluster in @segmentation.graphemes("e\u{301}🇺🇳x") {
clusters.push(cluster.to_owned())
}
debug_inspect(
clusters,
content=(
#|["é", "🇺🇳", "x"]
),
)
}test {
let breaks = @segmentation.line_breaks("Hello world!")
inspect(breaks.next(), content="Hello ")
debug_inspect(breaks.opportunity(), content="Allowed")
inspect(breaks.next(), content="world!")
debug_inspect(breaks.opportunity(), content="Mandatory")
assert_true(breaks.next().is_empty())
}test {
debug_inspect(
@segmentation.sentences("Hello! Next.")
.iter()
.map(s => s.to_owned())
.collect(),
content="[\"Hello! \", \"Next.\"]",
)
}test {
debug_inspect(
@segmentation.word_segments("Hello, world!")
.iter()
.map(s => s.to_owned())
.collect(),
content="[\"Hello\", \",\", \" \", \"world\", \"!\"]",
)
}test {
debug_inspect(
@segmentation.words("Hello, world! 42")
.iter()
.map(s => s.to_owned())
.collect(),
content="[\"Hello\", \"world\", \"42\"]",
)
}Install
Download zipUnicode Text Segmentation for MoonBit