normalize

package
v0.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 23, 2026 License: MIT Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package normalize is the cleanup between parsing a document and splitting it: the same sentence written with a non-breaking space, a curly apostrophe or a decomposed accent should reach the extractor as one string, not three.

Every transform is a Step — a function from string to string — and steps compose into a Chain, so a caller assembles the pipeline the corpus needs instead of arguing with an options struct. Text and Clean are the two chains worth having by default.

The package also reads the values that end up as graph nodes: dates (Date), numbers (Number), quantities (Quantity) and sums of money (Money). Each is a Kind: it reads text under an Anchor — what the source says about how to read it — into a typed value, and writes that value in one canonical form. A reading returns an error rather than a string, because a date that failed to parse is not a date, and text with two readings is refused with ErrAmbiguous rather than read one way.

Index

Constants

View Source
const (
	UTF8    = "utf-8"
	UTF16LE = "utf-16le"
	UTF16BE = "utf-16be"
	CP1252  = "windows-1252"
	Latin1  = "iso-8859-1"
)

Encodings this package names. Detection is deliberately shallow: it tells UTF-8 and the UTF-16s apart exactly, and otherwise decides between the two single-byte encodings that account for nearly all Western legacy text.

Variables

View Source
var (
	// ErrAmbiguous means the text has more than one reading and the Anchor
	// does not say which: a day and a month in an order it does not give, a
	// time with no zone, a separator that may group digits or mark a
	// decimal, a currency sign several currencies use, a relative date with
	// no date to count from.
	ErrAmbiguous = errors.New("ambiguous")
	// ErrSyntax means the text is not a value of the kind at all.
	ErrSyntax = errors.New("not readable")
)

Errors the typed readers report, wrapped with the kind, the text and the reason. Test for them with errors.Is.

View Source
var Date = Kind[Span]{Name: "date", Parse: date, Canon: when}

Date reads a date or a time into the Span it names.

It reads ISO 8601 and RFC 3339 — 2023, 2023-03, 2023-03-01, 2023-03-01T10:00, 2023-03-01T10:00:00.5+09:00 — an interval of two RFC 3339 times joined by "/", English month names — March 2023, 1 March 2023, March 1, 2023, Mar. 2023 — all-numeric dates with /, . or - between the parts, and today, yesterday and tomorrow.

It refuses, with ErrAmbiguous, what it would otherwise have to guess: an all-numeric date that does not begin with its year when Anchor.Order is unset, a two-digit year, a date with no year, a time with no offset when Anchor.Zone is unset or names a zone where that clock time happens twice, and a relative date when Anchor.At is zero.

View Source
var Money = Kind[Amount]{
	Name:  "money",
	Parse: money,
	Canon: func(m Amount) string { return decimal(m.Value) + " " + m.Code },
}

Money reads a sum of money: a number, as Number reads it, with an ISO 4217 code before or after it — "USD 5", "5.00 EUR" — or with a sign only one currency writes — "€5", "5 zł", "US$5", "CA$5".

A sign several currencies write — "$", "£", "¥", "₩", "kr", "C$" — is refused with ErrAmbiguous: "¥" is the yen and the yuan, and "$" a dozen currencies. A code must be uppercase and on ISO 4217's list, current or withdrawn since 1999, so "ALL 5" is lek and "all 5" is not money.

View Source
var Number = Kind[*big.Rat]{Name: "number", Parse: number, Canon: decimal}

Number reads a number exactly, as a rational: "1,234.5" is 2469/2, with no float anywhere to round it. It reads a sign — "-", "+" or the minus sign — digits, one decimal mark and groups of three separated by the other mark, a space, a narrow or non-breaking space, or an apostrophe; and "p/q". Its canonical form has a point, no grouping and no trailing zeros, and a value with no finite decimal — which only "p/q" can give — is written "p/q".

Which mark is the decimal is the Anchor's to say. Without one, a mark is read where it can be one thing only: both marks present, the last is the decimal; one mark repeated, it groups; one mark once, with three digits after it and one to three before — "1,234", "1.234" — it could be either, and is refused with ErrAmbiguous.

View Source
var Quantity = Kind[Measure]{
	Name:  "quantity",
	Parse: measure,
	Canon: func(m Measure) string { return decimal(m.Value) + " " + m.Unit },
}

Quantity reads a number followed by its unit — "5 kg", "12.5%", "3 metres", "72°F" — reading the number as Number does. A unit written as a word is folded to its symbol where the word has one meaning: "kilograms" is kg, "litre" is L, "percent" is %. One that does not — "ton", "gallon", "pound", "ounce", each of which is two or three different units — is kept as written, as is any unit the table does not know. Nothing is converted.

Functions

func BOM

func BOM(b []byte) int

BOM reports the length in bytes of the byte order mark at the front of b, or zero if there is none. Slicing b past it removes the mark.

func Clean

func Clean(s string) string

Clean is the default cleanup for text headed into a single field or a similarity key: everything Text does, plus HTML removal, and the line structure flattened to single spaces.

func Control

func Control(s string) string

Control drops the characters that carry no text: C0 and C1 control codes other than tab and newline, the byte order mark wherever it turns up, and the soft hyphen, which is a line-breaking hint that survives copy and paste as an invisible character inside a word.

func Decode

func Decode(b []byte) string

Decode turns bytes into a Go string: byte order mark removed, encoding guessed, bytes that cannot be decoded replaced with U+FFFD. It never fails, because a pipeline that stops on one bad byte is worse than one that keeps a replacement character.

func DecodeAs

func DecodeAs(b []byte, enc string) string

DecodeAs turns bytes into a string using the named encoding, for callers who know it from a Content-Type header or an XML declaration. An unknown name falls back to the guess.

func Flat

func Flat(s string) string

Flat collapses every run of whitespace, newlines included, to a single space. Use it for text that is going into one field or into a comparison key, where the line structure is noise.

func Guess

func Guess(b []byte) (string, float64)

Guess names the encoding of b and how far to trust the answer, from 0 to 1. A byte order mark settles it; otherwise valid UTF-8 is taken as UTF-8, a regular pattern of zero bytes as UTF-16, and anything else as one of the single-byte encodings, chosen by whether the bytes reserved for C1 controls are in use.

func Lines

func Lines(s string) string

Lines settles line endings on "\n", so text that travelled through Windows or a classic Mac editor reads the same as text that did not.

func Lower

func Lower(s string) string

Lower returns s in lower case.

func Marks

func Marks(s string) string

Marks returns s without combining marks, so "Crème Brûlée" becomes "Creme Brulee". Letters that carry no mark are untouched.

func NFC

func NFC(s string) string

NFC returns s with characters composed: "e" plus a combining acute becomes "é". Text that is already NFC is returned unchanged.

func NFD

func NFD(s string) string

NFD returns s with characters decomposed: "é" becomes "e" plus a combining acute, and marks are put in canonical order.

func NFKC

func NFKC(s string) string

NFKC returns s with compatibility characters folded to their plain equivalents and the result composed: "fi" becomes "fi", "1" becomes "1".

func NFKD

func NFKD(s string) string

NFKD returns s folded like NFKC but left decomposed.

func Quotes

func Quotes(s string) string

Quotes folds curly quotes, dashes and ellipses to their ASCII spelling.

func Repair

func Repair(s string) string

Repair undoes mojibake: text that was UTF-8, read as Latin-1 or windows-1252, and stored that way, so "café" is sitting in the string as "café". It re-encodes the characters back to the bytes they came from and reads those as UTF-8, and only keeps the result if it decodes cleanly — text that was never damaged comes back untouched.

func Repeats

func Repeats(pages []string, share float64) []string

Repeats removes the lines that recur across pages — running heads, footers, page numbers — and returns the pages without them. A line counts as furniture when it shows up on at least share of the pages; share of zero or less means three fifths of them.

Lines are compared with their digits blanked, so "Page 1 of 40" and "Page 2 of 40" count as the same line and a bare page number matches every other bare page number.

func Space

func Space(s string) string

Space regularizes horizontal space without destroying the shape of the text: every kind of space becomes an ordinary one, runs collapse, trailing space goes, and a run of blank lines becomes a single blank line. Paragraphs survive, which is what a splitter wants.

Code is left exactly as written, because in code the spacing is the meaning: a CommonMark fenced block, from its opening fence through its closing one (or to the end, when it never closes), and an indented block — lines indented four columns or more that do not continue a paragraph — keep their indentation, their inner spacing, their trailing space and their blank lines. Line endings are settled first, as Lines settles them.

func Tags

func Tags(s string) string

Tags removes HTML markup and decodes character references, leaving a space where each element stood so that words do not run together. It leaves the spacing itself alone; follow it with Space or Flat.

Script and style elements go with their contents, since their text is code rather than prose.

func Text

func Text(s string) string

Text is the default cleanup for prose that keeps its shape: compose characters, settle line endings, drop control codes, fold typographic punctuation to ASCII and regularize spacing. Paragraph breaks survive.

func Title

func Title(s string) string

Title capitalizes the first letter of every word and lowers the rest.

func Upper

func Upper(s string) string

Upper returns s in upper case.

Types

type Amount added in v0.3.1

type Amount struct {
	Value *big.Rat
	Code  string
}

Amount is a sum of money: an exact value in a currency, named by its ISO 4217 code.

type Anchor added in v0.3.1

type Anchor struct {
	// At is the source's own date — when the letter was written, the page
	// published, the message sent — and relative dates such as "yesterday"
	// are counted from it, on its calendar. It is never the time of reading:
	// a document says "yesterday" about the day before it was written, and
	// nothing here calls time.Now. Zero refuses a relative date.
	At time.Time
	// Zone places a time written without an offset. Nil refuses one.
	Zone *time.Location
	// Order is the order of day and month in an all-numeric date. Zero
	// refuses one that does not begin with its year.
	Order Order
	// Point is the decimal mark, '.' or ','; the other is then a digit group
	// separator. Zero reads a mark only where it can be one thing, and
	// refuses "1,234" and "1.234", which can be either.
	Point rune
}

Anchor is what a source says about how to read the values in it: the context a date or a number needs and the text alone does not carry. The zero Anchor assumes nothing, and anything whose reading depends on it is refused rather than read one way by default.

type Chain

type Chain []Step

Chain applies steps in order. The zero Chain returns its input unchanged.

func (Chain) Run

func (c Chain) Run(s string) string

Run applies every step in the chain to s.

type Datatype added in v0.3.1

type Datatype interface {
	// String is the kind's name.
	String() string
	// Norm reads s under a and writes it canonically.
	Norm(a Anchor, s string) (string, error)
}

Datatype is a Kind seen without its Go type, for code that holds several kinds side by side — a schema whose properties each name one — and needs only the canonical text.

type Grain added in v0.3.1

type Grain int

Grain is the unit a date was written to. The zero Grain is a span given by its bounds alone, as an ISO 8601 interval.

const (
	Year Grain = iota + 1
	Month
	Day
	Minute
	Second
	Nano
)

The grains a date can be written to. A time with a fraction of a second is an instant, and spans one nanosecond.

type Kind added in v0.3.1

type Kind[T any] struct {
	Name  string
	Parse func(Anchor, string) (T, error)
	Canon func(T) string
}

Kind is one kind of value: how to read it from text under an Anchor, and how to write it in its one canonical form.

Canon writes text that Parse reads back under Anchor{Point: '.'} to the same value — ISO 8601 dates with their offsets, numbers with a point and no grouping — so Canon∘Parse settles every spelling of a value on one string, and applying it again changes nothing.

func (Kind[T]) Norm added in v0.3.1

func (k Kind[T]) Norm(a Anchor, s string) (string, error)

Norm reads s under a and writes the value in its canonical form.

func (Kind[T]) String added in v0.3.1

func (k Kind[T]) String() string

String returns the kind's name.

type Measure added in v0.3.1

type Measure struct {
	Value *big.Rat
	Unit  string
}

Measure is a quantity: an exact number of a unit.

type Order added in v0.3.1

type Order int

Order is the order of the day and the month in an all-numeric date.

const (
	DMY Order = iota + 1 // 31/12/2023
	MDY                  // 12/31/2023
)

The two orders in use. A date that begins with a four-digit year is read year, month, day whatever the Order.

type Span added in v0.3.1

type Span struct {
	From, Until time.Time
	Grain       Grain
}

Span is the stretch of time a date names, half-open: From is its first instant and Until the first instant after it. "March 2023" is [2023-03-01, 2023-04-01), so a month contains its days, two spans overlap exactly when the times they name do, and a day is never mistaken for its midnight.

A span of a day or longer is a calendar date, and names days, not instants in some zone: its bounds are midnights in UTC standing for those dates. A span of a minute or shorter is a time, and its bounds carry the offset it was written with or the one Anchor.Zone gave it.

type Step

type Step func(string) string

Step is one text transform. Every exported function of the form func(string) string in this package is a Step and can be used as one.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL