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
- Variables
- func BOM(b []byte) int
- func Clean(s string) string
- func Control(s string) string
- func Decode(b []byte) string
- func DecodeAs(b []byte, enc string) string
- func Flat(s string) string
- func Guess(b []byte) (string, float64)
- func Lines(s string) string
- func Lower(s string) string
- func Marks(s string) string
- func NFC(s string) string
- func NFD(s string) string
- func NFKC(s string) string
- func NFKD(s string) string
- func Quotes(s string) string
- func Repair(s string) string
- func Repeats(pages []string, share float64) []string
- func Space(s string) string
- func Tags(s string) string
- func Text(s string) string
- func Title(s string) string
- func Upper(s string) string
- type Amount
- type Anchor
- type Chain
- type Datatype
- type Grain
- type Kind
- type Measure
- type Order
- type Span
- type Step
Constants ¶
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 ¶
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.
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.
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.
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 Marks ¶
Marks returns s without combining marks, so "Crème Brûlée" becomes "Creme Brulee". Letters that carry no mark are untouched.
func NFC ¶
NFC returns s with characters composed: "e" plus a combining acute becomes "é". Text that is already NFC is returned unchanged.
func NFD ¶
NFD returns s with characters decomposed: "é" becomes "e" plus a combining acute, and marks are put in canonical order.
func NFKC ¶
NFKC returns s with compatibility characters folded to their plain equivalents and the result composed: "fi" becomes "fi", "1" becomes "1".
func Repair ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
Types ¶
type Amount ¶ added in v0.3.1
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.
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.
type Kind ¶ added in v0.3.1
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.
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.
type Span ¶ added in v0.3.1
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.