linguabase 1.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: linguabase
3
+ Version: 1.1.0
4
+ Summary: A thesaurus of 100,000 English words and phrases, with the larger Linguabase tables a call away. Public domain.
5
+ Author-email: Michael Douma <linguabase@idea.org>
6
+ License-Expression: CC0-1.0
7
+ Project-URL: Homepage, https://www.linguabase.org
8
+ Project-URL: Repository, https://github.com/michaeldouma/linguabase
9
+ Project-URL: Data, https://doi.org/10.5281/zenodo.20788427
10
+ Keywords: thesaurus,english,word associations,antonyms,word games,lexicon
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Text Processing :: Linguistic
13
+ Classifier: Natural Language :: English
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ Provides-Extra: tables
17
+ Requires-Dist: duckdb>=1.0; extra == "tables"
18
+ Requires-Dist: certifi; extra == "tables"
19
+
20
+ # linguabase for Python
21
+
22
+ A thesaurus of about 100,000 English words and phrases, inside the package. Nothing is downloaded.
23
+
24
+ ```sh
25
+ pip install "git+https://github.com/michaeldouma/linguabase#subdirectory=python"
26
+ ```
27
+
28
+ ```python
29
+ import linguabase as lb
30
+
31
+ lb.related("cold", 5) # ['snow', 'ice cold', 'frostbite', 'winter', 'cold snap']
32
+ lb.related("night sky") # ['constellation', 'stargazing', 'looking up', ...] up to 30
33
+ lb.rank("cold") # 517: its familiarity rank among all English terms; 1 is the most familiar
34
+ ```
35
+
36
+ ```sh
37
+ linguabase related cold
38
+ linguabase rank cold
39
+ ```
40
+
41
+ The package is 13 MB and has no dependencies.
42
+
43
+ ## More words, longer lists
44
+
45
+ Two larger files are attached to the [release](https://github.com/michaeldouma/linguabase/releases/tag/v1.1.0). Download one and load it:
46
+
47
+ ```python
48
+ lb.load("related-words-400k.txt.gz") # 397,130 words and phrases, up to 30 related words each (47 MB)
49
+ lb.load("related-words-deep.txt.gz") # the 100,000, up to 100 related words each (29 MB)
50
+ ```
51
+
52
+ ## The full tables
53
+
54
+ Opposites, senses, word families, definitions, clues and scores are in the Linguabase tables, which live on Hugging Face, Zenodo and Kaggle. With the `tables` option, each table is fetched from Hugging Face the first time a function needs it and kept in `~/.cache/linguabase`:
55
+
56
+ ```sh
57
+ pip install "linguabase[tables] @ git+https://github.com/michaeldouma/linguabase#subdirectory=python"
58
+ ```
59
+
60
+ ```python
61
+ lb.related("cold", tier="core") # the whole list, for any of the 400,000 core words; tier="full" for all 2 million terms
62
+ lb.opposites("cold") # {'temperature': [('hot', 7), ('warm', 7), ...], 'emotional warmth': [...], ...}
63
+ lb.senses("crane") # ['bird', 'machine', 'neck', 'origami']
64
+ lb.related_by_sense("crane") # {'bird': ['heron', 'stork', ...], 'machine': ['hoist', 'boom', ...], ...}
65
+ lb.family("bridge") # ['bridges', 'bridging', 'bridged', 'drawbridge', ...]
66
+ lb.definition("elephant") # 'An elephant is a massive land mammal ...'
67
+ lb.clues("key") # {'W1': 'Crucial', 'SYN': 'Essential', 'CAT': 'Hardware or music term', ...}
68
+ lb.familiarity("night sky") # {'score': 0.9968, 'rank': 5648, 'in_core': True}
69
+ lb.scores("elephant") # {'iconability': 0.85, 'content_rating': 'G', ...}
70
+ ```
71
+
72
+ The tables are large: the related words for the core are 132 MB, and a message says so before each download. `lb.path("antonyms")` returns the local Parquet file, for your own queries. If you already have the download, set `LINGUABASE_DATA` to its folder and nothing is fetched. The option installs `duckdb` and `certifi`.
73
+
74
+ Python 3.9 or later. Data: Linguabase 1.1, public domain (CC0).
@@ -0,0 +1,55 @@
1
+ # linguabase for Python
2
+
3
+ A thesaurus of about 100,000 English words and phrases, inside the package. Nothing is downloaded.
4
+
5
+ ```sh
6
+ pip install "git+https://github.com/michaeldouma/linguabase#subdirectory=python"
7
+ ```
8
+
9
+ ```python
10
+ import linguabase as lb
11
+
12
+ lb.related("cold", 5) # ['snow', 'ice cold', 'frostbite', 'winter', 'cold snap']
13
+ lb.related("night sky") # ['constellation', 'stargazing', 'looking up', ...] up to 30
14
+ lb.rank("cold") # 517: its familiarity rank among all English terms; 1 is the most familiar
15
+ ```
16
+
17
+ ```sh
18
+ linguabase related cold
19
+ linguabase rank cold
20
+ ```
21
+
22
+ The package is 13 MB and has no dependencies.
23
+
24
+ ## More words, longer lists
25
+
26
+ Two larger files are attached to the [release](https://github.com/michaeldouma/linguabase/releases/tag/v1.1.0). Download one and load it:
27
+
28
+ ```python
29
+ lb.load("related-words-400k.txt.gz") # 397,130 words and phrases, up to 30 related words each (47 MB)
30
+ lb.load("related-words-deep.txt.gz") # the 100,000, up to 100 related words each (29 MB)
31
+ ```
32
+
33
+ ## The full tables
34
+
35
+ Opposites, senses, word families, definitions, clues and scores are in the Linguabase tables, which live on Hugging Face, Zenodo and Kaggle. With the `tables` option, each table is fetched from Hugging Face the first time a function needs it and kept in `~/.cache/linguabase`:
36
+
37
+ ```sh
38
+ pip install "linguabase[tables] @ git+https://github.com/michaeldouma/linguabase#subdirectory=python"
39
+ ```
40
+
41
+ ```python
42
+ lb.related("cold", tier="core") # the whole list, for any of the 400,000 core words; tier="full" for all 2 million terms
43
+ lb.opposites("cold") # {'temperature': [('hot', 7), ('warm', 7), ...], 'emotional warmth': [...], ...}
44
+ lb.senses("crane") # ['bird', 'machine', 'neck', 'origami']
45
+ lb.related_by_sense("crane") # {'bird': ['heron', 'stork', ...], 'machine': ['hoist', 'boom', ...], ...}
46
+ lb.family("bridge") # ['bridges', 'bridging', 'bridged', 'drawbridge', ...]
47
+ lb.definition("elephant") # 'An elephant is a massive land mammal ...'
48
+ lb.clues("key") # {'W1': 'Crucial', 'SYN': 'Essential', 'CAT': 'Hardware or music term', ...}
49
+ lb.familiarity("night sky") # {'score': 0.9968, 'rank': 5648, 'in_core': True}
50
+ lb.scores("elephant") # {'iconability': 0.85, 'content_rating': 'G', ...}
51
+ ```
52
+
53
+ The tables are large: the related words for the core are 132 MB, and a message says so before each download. `lb.path("antonyms")` returns the local Parquet file, for your own queries. If you already have the download, set `LINGUABASE_DATA` to its folder and nothing is fetched. The option installs `duckdb` and `certifi`.
54
+
55
+ Python 3.9 or later. Data: Linguabase 1.1, public domain (CC0).
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "linguabase"
7
+ version = "1.1.0"
8
+ description = "A thesaurus of 100,000 English words and phrases, with the larger Linguabase tables a call away. Public domain."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "CC0-1.0"
12
+ authors = [{ name = "Michael Douma", email = "linguabase@idea.org" }]
13
+ keywords = ["thesaurus", "english", "word associations", "antonyms", "word games", "lexicon"]
14
+ dependencies = []
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Text Processing :: Linguistic",
18
+ "Natural Language :: English",
19
+ ]
20
+
21
+ [project.optional-dependencies]
22
+ tables = ["duckdb>=1.0", "certifi"]
23
+
24
+ [project.urls]
25
+ Homepage = "https://www.linguabase.org"
26
+ Repository = "https://github.com/michaeldouma/linguabase"
27
+ Data = "https://doi.org/10.5281/zenodo.20788427"
28
+
29
+ [project.scripts]
30
+ linguabase = "linguabase.__main__:main"
31
+
32
+ [tool.setuptools.packages.find]
33
+ where = ["src"]
34
+
35
+ [tool.setuptools.package-data]
36
+ linguabase = ["data/*.gz"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,309 @@
1
+ """Look up English words in Linguabase.
2
+
3
+ import linguabase as lb
4
+ lb.related("cold") # ['snow', 'ice cold', 'frostbite', ...] from data inside the package
5
+ lb.rank("cold") # its familiarity rank; 1 is the most familiar
6
+ lb.opposites("cold") # {'temperature': [('hot', 7), ...], ...} fetches a table on first use
7
+
8
+ related() and rank() read a thesaurus that comes with the package: about
9
+ 100,000 words and phrases, up to 30 related words each. Nothing is downloaded.
10
+
11
+ For more words or longer lists, load a larger thesaurus file with load(), or
12
+ install the tables option (pip install "linguabase[tables]") and pass
13
+ tier="core" (400,000 words) or tier="full" (2 million terms). The other
14
+ functions read the Linguabase tables and need that option too. Each table is
15
+ fetched from Hugging Face the first time it is needed and kept in a cache
16
+ folder; to use a copy you already have, set LINGUABASE_DATA to the folder
17
+ that holds vocabulary/, associations/ and the other table folders.
18
+
19
+ Data: Linguabase 1.1, public domain (CC0).
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import gzip
24
+ import os
25
+ import ssl
26
+ import sys
27
+ import urllib.error
28
+ import urllib.request
29
+ from pathlib import Path
30
+
31
+ __version__ = "1.1.0"
32
+ DATA_VERSION = "1.1"
33
+
34
+ # The Hugging Face revision of Linguabase 1.1, so every install reads the same data.
35
+ _REVISION = "c07b767cd80fb8203ed5016ef721c15459f7ad8a"
36
+ _BASE = "https://huggingface.co/datasets/linguabase/linguabase/resolve/" + _REVISION
37
+
38
+ # Parquet sizes in MB, shown before a download.
39
+ _SIZES = {
40
+ ("vocabulary", "core"): 6, ("vocabulary", "full"): 24,
41
+ ("associations", "core"): 132, ("associations", "full"): 511,
42
+ ("senses", "core"): 7, ("senses", "full"): 27,
43
+ ("sense_associations", "core"): 162, ("sense_associations", "full"): 622,
44
+ ("word_families", "core"): 12, ("word_families", "full"): 54,
45
+ ("antonyms", "core"): 120, ("antonyms", "full"): 299,
46
+ ("definitions", "core"): 50, ("definitions", "full"): 241,
47
+ ("clues", "core"): 114, ("clues", "full"): 454,
48
+ ("scores_labels", "core"): 4, ("scores_labels", "full"): 13,
49
+ ("opposite_pairs", "full"): 49, ("category_antonyms", "full"): 34,
50
+ ("categories", "full"): 88, ("topics", "full"): 88,
51
+ }
52
+ _SINGLE = {"opposite_pairs", "category_antonyms", "categories", "topics"}
53
+ TABLES = sorted({table for table, _ in _SIZES})
54
+
55
+ # ---------------------------------------------------------------- the thesaurus in the package
56
+
57
+ _DATA = Path(__file__).parent / "data"
58
+ _lists = None # headword -> "related,related,..." (split on lookup)
59
+ _ranks = None # headword -> familiarity rank
60
+
61
+
62
+ def _read_lines(file):
63
+ opener = gzip.open if str(file).endswith(".gz") else open
64
+ with opener(file, "rt", encoding="utf-8") as f:
65
+ for line in f:
66
+ if line.endswith("\n"):
67
+ line = line[:-1]
68
+ if line:
69
+ yield line
70
+
71
+
72
+ def load(file=None) -> int:
73
+ """Use another thesaurus file for related(): a headword, then its related
74
+ words, commas between, one line per headword (.txt or .txt.gz). Larger
75
+ cuts are attached to the releases at github.com/michaeldouma/linguabase.
76
+ Call with no argument to go back to the one in the package.
77
+ Returns the number of headwords.
78
+ """
79
+ global _lists
80
+ lists = {}
81
+ for line in _read_lines(file or _DATA / "related-words.txt.gz"):
82
+ head, _, rest = line.partition(",")
83
+ lists[head] = rest
84
+ _lists = lists
85
+ return len(lists)
86
+
87
+
88
+ def _lookup(table, word):
89
+ if word in table:
90
+ return table[word]
91
+ lower = word.lower()
92
+ return table.get(lower) if lower != word else None
93
+
94
+
95
+ def related(word: str, n: int | None = None, tier: str | None = None) -> list[str]:
96
+ """Related words and phrases, strongest first.
97
+
98
+ By default this reads the thesaurus in the package: about 100,000 words
99
+ and phrases, up to 30 related words each. tier="core" reads the
100
+ associations table for the 400,000 core words (about 75 related words
101
+ each), and tier="full" the table for all 2 million terms; either fetches
102
+ that table the first time.
103
+ """
104
+ if tier is None:
105
+ if _lists is None:
106
+ load()
107
+ found = _lookup(_lists, word)
108
+ items = found.split(",") if found else []
109
+ else:
110
+ rows = _rows("associations", word, "associates", tier)
111
+ items = list(rows[0][0]) if rows else []
112
+ return items[:n] if n else items
113
+
114
+
115
+ def rank(word: str) -> int | None:
116
+ """Familiarity rank among all English terms; 1 is the most familiar.
117
+ Read from the package, for the words of its thesaurus. None for other words;
118
+ familiarity() covers all 2 million terms."""
119
+ global _ranks
120
+ if _ranks is None:
121
+ ranks = {}
122
+ for line in _read_lines(_DATA / "familiarity.txt.gz"):
123
+ head, _, value = line.partition("\t")
124
+ ranks[head] = int(value)
125
+ _ranks = ranks
126
+ return _lookup(_ranks, word)
127
+
128
+
129
+ def words() -> list[str]:
130
+ """Every headword of the thesaurus in use, in alphabetical order."""
131
+ if _lists is None:
132
+ load()
133
+ return list(_lists)
134
+
135
+
136
+ # ---------------------------------------------------------------- the tables
137
+
138
+ _con = None
139
+
140
+
141
+ def _connection():
142
+ global _con
143
+ if _con is None:
144
+ try:
145
+ import duckdb
146
+ except ImportError:
147
+ raise ImportError(
148
+ 'this reads the Linguabase tables, which needs the "tables" option: '
149
+ 'pip install "linguabase[tables]"') from None
150
+ _con = duckdb.connect()
151
+ return _con
152
+
153
+
154
+ def cache_dir() -> Path:
155
+ """The folder downloaded tables are kept in."""
156
+ root = os.environ.get("LINGUABASE_CACHE")
157
+ if root:
158
+ return Path(root)
159
+ base = os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache")
160
+ return Path(base) / "linguabase" / DATA_VERSION
161
+
162
+
163
+ def _open(url: str):
164
+ # Some Python installs (python.org builds on macOS, for one) have no root
165
+ # certificates of their own, so use certifi's.
166
+ try:
167
+ import certifi
168
+ context = ssl.create_default_context(cafile=certifi.where())
169
+ except Exception:
170
+ context = None
171
+ return urllib.request.urlopen(url, context=context)
172
+
173
+
174
+ def path(table: str, tier: str = "core") -> str:
175
+ """The local Parquet file for a table, downloading it first if needed.
176
+
177
+ tier is "core" (400,000 curated headwords) or "full" (about 2 million terms).
178
+ The four tables keyed on a topic or category have one tier.
179
+ """
180
+ if table not in TABLES:
181
+ raise ValueError(f"unknown table {table!r}; the tables are: {', '.join(TABLES)}")
182
+ if table in _SINGLE:
183
+ tier = "full"
184
+ elif tier not in ("core", "full"):
185
+ raise ValueError('tier must be "core" or "full"')
186
+ name = f"{table}.{tier}.parquet"
187
+
188
+ local = os.environ.get("LINGUABASE_DATA")
189
+ if local:
190
+ p = Path(local) / table / name
191
+ if not p.exists():
192
+ raise FileNotFoundError(f"{p} not found (LINGUABASE_DATA is set to {local})")
193
+ return str(p)
194
+
195
+ p = cache_dir() / table / name
196
+ if not p.exists():
197
+ size = _SIZES[(table, tier)]
198
+ print(f"linguabase: downloading {name} ({size} MB) from Hugging Face to {p.parent}, once", file=sys.stderr)
199
+ tmp = p.with_suffix(".part")
200
+ try:
201
+ response = _open(f"{_BASE}/{table}/{name}")
202
+ except urllib.error.URLError as e:
203
+ if isinstance(e.reason, ssl.SSLCertVerificationError):
204
+ raise RuntimeError(
205
+ "this Python has no root certificates, so the download cannot be verified; "
206
+ 'install them with: pip install "linguabase[tables]"') from None
207
+ raise
208
+ p.parent.mkdir(parents=True, exist_ok=True)
209
+ with response as r, open(tmp, "wb") as f:
210
+ while True:
211
+ chunk = r.read(1 << 20)
212
+ if not chunk:
213
+ break
214
+ f.write(chunk)
215
+ tmp.replace(p)
216
+ return str(p)
217
+
218
+
219
+ def _rows(table: str, word: str, columns: str = "*", tier: str = "core"):
220
+ con = _connection() # first, so a missing option is reported before anything is downloaded
221
+ file = path(table, tier)
222
+ sql = f"SELECT {columns} FROM read_parquet(?) WHERE word = ?"
223
+ rows = con.execute(sql, [file, word]).fetchall()
224
+ if not rows and word != word.lower():
225
+ rows = con.execute(sql, [file, word.lower()]).fetchall()
226
+ return rows
227
+
228
+
229
+ def familiarity(word: str) -> dict | None:
230
+ """Score (0 to 1), rank (1 is the most familiar) and core membership, for any of the 2 million terms.
231
+ Reads the vocabulary table."""
232
+ rows = _rows("vocabulary", word, "familiarity_score, familiarity_rank, in_core", "full")
233
+ if not rows:
234
+ return None
235
+ score, rank_, in_core = rows[0]
236
+ return {"score": score, "rank": rank_, "in_core": in_core}
237
+
238
+
239
+ def opposites(word: str, tier: str = "core") -> dict[str, list[tuple[str, int]]]:
240
+ """Opposites grouped by axis, each with a strength from 1 to 7."""
241
+ out: dict[str, list[tuple[str, int]]] = {}
242
+ for axis, items in _rows("antonyms", word, "axis, opposites", tier):
243
+ pairs = []
244
+ for item in items:
245
+ term, _, rating = item.rpartition(":")
246
+ pairs.append((term, int(rating)) if rating.isdigit() else (item, 0))
247
+ out[axis] = pairs
248
+ return out
249
+
250
+
251
+ def senses(word: str, tier: str = "core") -> list[str]:
252
+ """Short labels for the word's senses."""
253
+ rows = _rows("senses", word, "sense_labels", tier)
254
+ return list(rows[0][0]) if rows else []
255
+
256
+
257
+ def related_by_sense(word: str, tier: str = "core") -> dict[str, list[str]]:
258
+ """Related words for each sense of the word."""
259
+ return {sense: list(items) for sense, items in _rows("sense_associations", word, "sense, associates", tier)}
260
+
261
+
262
+ def family(word: str, tier: str = "core") -> list[str]:
263
+ """Words that share the word's root."""
264
+ rows = _rows("word_families", word, "relatives", tier)
265
+ return list(rows[0][0]) if rows else []
266
+
267
+
268
+ def definition(word: str, tier: str = "core") -> str | None:
269
+ """A one-paragraph definition. Text in {braces} is meant to be italic."""
270
+ rows = _rows("definitions", word, "definition", tier)
271
+ return rows[0][0] if rows else None
272
+
273
+
274
+ def clues(word: str, tier: str = "core") -> dict[str, str]:
275
+ """The word's clues by style (W1, SYN, DEF, FIG ...), without the 'n/a' cells or the stars."""
276
+ con = _connection()
277
+ file = path("clues", tier)
278
+ sql = "SELECT * FROM read_parquet(?) WHERE word = ? AND meaning = 'main'"
279
+ cur = con.execute(sql, [file, word])
280
+ row = cur.fetchone()
281
+ if row is None and word != word.lower():
282
+ cur = con.execute(sql, [file, word.lower()])
283
+ row = cur.fetchone()
284
+ if row is None:
285
+ return {}
286
+ out = {}
287
+ for column, value in zip(cur.description, row):
288
+ name = column[0]
289
+ if name.startswith("clue_") and value and value != "n/a":
290
+ out[name[5:]] = value.rstrip("* ").rstrip()
291
+ return out
292
+
293
+
294
+ def scores(word: str, tier: str = "core") -> dict:
295
+ """The word's scores and labels: content rating, sensitivity, drawability and the rest."""
296
+ con = _connection()
297
+ file = path("scores_labels", tier)
298
+ cur = con.execute("SELECT * FROM read_parquet(?) WHERE word = ?", [file, word])
299
+ row = cur.fetchone()
300
+ if row is None:
301
+ return {}
302
+ return {d[0]: v for d, v in zip(cur.description, row) if d[0] != "word" and v is not None}
303
+
304
+
305
+ __all__ = [
306
+ "related", "rank", "words", "load",
307
+ "familiarity", "opposites", "senses", "related_by_sense", "family", "definition", "clues", "scores",
308
+ "path", "cache_dir", "TABLES", "DATA_VERSION",
309
+ ]
@@ -0,0 +1,57 @@
1
+ """Command line: linguabase related cold | linguabase opposites cold | linguabase define elephant"""
2
+ import sys
3
+
4
+ import linguabase as lb
5
+
6
+ USAGE = """usage: linguabase COMMAND WORD
7
+
8
+ commands:
9
+ related related words, strongest first (from the package; nothing is downloaded)
10
+ rank familiarity rank, 1 is the most familiar (from the package)
11
+ opposites opposites by axis
12
+ senses the word's senses, with related words for each
13
+ family words that share its root
14
+ define a one-paragraph definition
15
+ clues clues by style
16
+ familiarity score and rank, for any of the 2 million terms
17
+
18
+ All but the first two fetch a table from Hugging Face the first time.
19
+ """
20
+
21
+
22
+ def main(argv=None):
23
+ argv = sys.argv[1:] if argv is None else argv
24
+ if len(argv) < 2 or argv[0] in ("-h", "--help"):
25
+ print(USAGE, end="")
26
+ return 0 if argv and argv[0] in ("-h", "--help") else 2
27
+ command, word = argv[0], " ".join(argv[1:])
28
+ if command == "related":
29
+ print(", ".join(lb.related(word)))
30
+ elif command == "rank":
31
+ r = lb.rank(word)
32
+ print("not found" if r is None else r)
33
+ elif command == "opposites":
34
+ for axis, pairs in lb.opposites(word).items():
35
+ print(f"{axis}: " + ", ".join(term for term, _ in pairs))
36
+ elif command == "senses":
37
+ by_sense = lb.related_by_sense(word)
38
+ for sense in lb.senses(word) or by_sense:
39
+ print(f"{sense}: " + ", ".join(by_sense.get(sense, [])[:12]))
40
+ elif command == "family":
41
+ print(", ".join(lb.family(word)))
42
+ elif command == "define":
43
+ print(lb.definition(word) or "")
44
+ elif command == "clues":
45
+ for style, clue in lb.clues(word).items():
46
+ print(f"{style}: {clue}")
47
+ elif command == "familiarity":
48
+ f = lb.familiarity(word)
49
+ print("not found" if f is None else f"score {f['score']:.4f}, rank {f['rank']:,}" if f["rank"] else "no score")
50
+ else:
51
+ print(USAGE, end="")
52
+ return 2
53
+ return 0
54
+
55
+
56
+ if __name__ == "__main__":
57
+ sys.exit(main())
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: linguabase
3
+ Version: 1.1.0
4
+ Summary: A thesaurus of 100,000 English words and phrases, with the larger Linguabase tables a call away. Public domain.
5
+ Author-email: Michael Douma <linguabase@idea.org>
6
+ License-Expression: CC0-1.0
7
+ Project-URL: Homepage, https://www.linguabase.org
8
+ Project-URL: Repository, https://github.com/michaeldouma/linguabase
9
+ Project-URL: Data, https://doi.org/10.5281/zenodo.20788427
10
+ Keywords: thesaurus,english,word associations,antonyms,word games,lexicon
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Text Processing :: Linguistic
13
+ Classifier: Natural Language :: English
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ Provides-Extra: tables
17
+ Requires-Dist: duckdb>=1.0; extra == "tables"
18
+ Requires-Dist: certifi; extra == "tables"
19
+
20
+ # linguabase for Python
21
+
22
+ A thesaurus of about 100,000 English words and phrases, inside the package. Nothing is downloaded.
23
+
24
+ ```sh
25
+ pip install "git+https://github.com/michaeldouma/linguabase#subdirectory=python"
26
+ ```
27
+
28
+ ```python
29
+ import linguabase as lb
30
+
31
+ lb.related("cold", 5) # ['snow', 'ice cold', 'frostbite', 'winter', 'cold snap']
32
+ lb.related("night sky") # ['constellation', 'stargazing', 'looking up', ...] up to 30
33
+ lb.rank("cold") # 517: its familiarity rank among all English terms; 1 is the most familiar
34
+ ```
35
+
36
+ ```sh
37
+ linguabase related cold
38
+ linguabase rank cold
39
+ ```
40
+
41
+ The package is 13 MB and has no dependencies.
42
+
43
+ ## More words, longer lists
44
+
45
+ Two larger files are attached to the [release](https://github.com/michaeldouma/linguabase/releases/tag/v1.1.0). Download one and load it:
46
+
47
+ ```python
48
+ lb.load("related-words-400k.txt.gz") # 397,130 words and phrases, up to 30 related words each (47 MB)
49
+ lb.load("related-words-deep.txt.gz") # the 100,000, up to 100 related words each (29 MB)
50
+ ```
51
+
52
+ ## The full tables
53
+
54
+ Opposites, senses, word families, definitions, clues and scores are in the Linguabase tables, which live on Hugging Face, Zenodo and Kaggle. With the `tables` option, each table is fetched from Hugging Face the first time a function needs it and kept in `~/.cache/linguabase`:
55
+
56
+ ```sh
57
+ pip install "linguabase[tables] @ git+https://github.com/michaeldouma/linguabase#subdirectory=python"
58
+ ```
59
+
60
+ ```python
61
+ lb.related("cold", tier="core") # the whole list, for any of the 400,000 core words; tier="full" for all 2 million terms
62
+ lb.opposites("cold") # {'temperature': [('hot', 7), ('warm', 7), ...], 'emotional warmth': [...], ...}
63
+ lb.senses("crane") # ['bird', 'machine', 'neck', 'origami']
64
+ lb.related_by_sense("crane") # {'bird': ['heron', 'stork', ...], 'machine': ['hoist', 'boom', ...], ...}
65
+ lb.family("bridge") # ['bridges', 'bridging', 'bridged', 'drawbridge', ...]
66
+ lb.definition("elephant") # 'An elephant is a massive land mammal ...'
67
+ lb.clues("key") # {'W1': 'Crucial', 'SYN': 'Essential', 'CAT': 'Hardware or music term', ...}
68
+ lb.familiarity("night sky") # {'score': 0.9968, 'rank': 5648, 'in_core': True}
69
+ lb.scores("elephant") # {'iconability': 0.85, 'content_rating': 'G', ...}
70
+ ```
71
+
72
+ The tables are large: the related words for the core are 132 MB, and a message says so before each download. `lb.path("antonyms")` returns the local Parquet file, for your own queries. If you already have the download, set `LINGUABASE_DATA` to its folder and nothing is fetched. The option installs `duckdb` and `certifi`.
73
+
74
+ Python 3.9 or later. Data: Linguabase 1.1, public domain (CC0).
@@ -0,0 +1,13 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/linguabase/__init__.py
4
+ src/linguabase/__main__.py
5
+ src/linguabase.egg-info/PKG-INFO
6
+ src/linguabase.egg-info/SOURCES.txt
7
+ src/linguabase.egg-info/dependency_links.txt
8
+ src/linguabase.egg-info/entry_points.txt
9
+ src/linguabase.egg-info/requires.txt
10
+ src/linguabase.egg-info/top_level.txt
11
+ src/linguabase/data/familiarity.txt.gz
12
+ src/linguabase/data/related-words.txt.gz
13
+ tests/test_basic.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ linguabase = linguabase.__main__:main
@@ -0,0 +1,4 @@
1
+
2
+ [tables]
3
+ duckdb>=1.0
4
+ certifi
@@ -0,0 +1 @@
1
+ linguabase
@@ -0,0 +1,72 @@
1
+ """The first tests need nothing. The table tests need LINGUABASE_DATA pointing at a full download.
2
+
3
+ python -m pytest python/tests
4
+ """
5
+ import os
6
+
7
+ import pytest
8
+
9
+ import linguabase as lb
10
+
11
+ tables = pytest.mark.skipif(not os.environ.get("LINGUABASE_DATA"), reason="set LINGUABASE_DATA to a download")
12
+
13
+
14
+ def test_related_from_the_package():
15
+ cold = lb.related("cold")
16
+ assert len(cold) == 30 and cold[:3] == ["snow", "ice cold", "frostbite"]
17
+ assert lb.related("cold", 2) == ["snow", "ice cold"]
18
+ assert lb.related("Cold") == cold # falls back to lowercase
19
+ assert lb.related("zzzznotaword") == []
20
+ assert "stargazing" in lb.related("night sky")
21
+ assert len(lb.words()) == 99555
22
+
23
+
24
+ def test_rank_from_the_package():
25
+ assert lb.rank("the") == 1
26
+ assert lb.rank("night sky") == 5648
27
+ assert lb.rank("zzzznotaword") is None
28
+
29
+
30
+ def test_load(tmp_path):
31
+ f = tmp_path / "mine.txt"
32
+ f.write_text("cold,hot,warm\nsun,moon\n", encoding="utf-8")
33
+ assert lb.load(f) == 2
34
+ assert lb.related("cold") == ["hot", "warm"]
35
+ assert lb.load() == 99555
36
+ assert len(lb.related("cold")) == 30
37
+
38
+
39
+ @tables
40
+ def test_related_from_the_tables():
41
+ words = lb.related("elephant", tier="core")
42
+ assert words[:3] == ["tusk", "pachyderm", "trunk"] and len(words) == 125
43
+ assert lb.related("elephant", 5, tier="full") == words[:5]
44
+
45
+
46
+ @tables
47
+ def test_familiarity():
48
+ f = lb.familiarity("elephant")
49
+ assert f["rank"] == 1461 and f["in_core"] and 0.99 < f["score"] <= 1
50
+ assert lb.familiarity("zzzznotaword") is None
51
+
52
+
53
+ @tables
54
+ def test_opposites_and_senses():
55
+ o = lb.opposites("cold")
56
+ assert ("hot", 7) in o["temperature"] and len(o) == 6
57
+ assert "circus" in lb.senses("elephant")
58
+ assert lb.related_by_sense("crane").keys() == {"bird", "machine", "neck", "origami"}
59
+
60
+
61
+ @tables
62
+ def test_text():
63
+ assert lb.definition("elephant").startswith("An elephant is")
64
+ c = lb.clues("key")
65
+ assert c["W1"] == "Crucial" and not c["FIG"].endswith("*")
66
+ assert lb.family("bridge")[0] == "bridges"
67
+ assert lb.scores("elephant")["content_rating"] == "G"
68
+
69
+
70
+ def test_errors():
71
+ with pytest.raises(ValueError):
72
+ lb.path("nope")