svlang 0.1.0__py3-none-any.whl

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.
svlang/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """svlang — Swedish NLP toolkit for translators."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,9 @@
1
+ """Built-in checkers."""
2
+
3
+ from svlang.checkers.consistency import ConsistencyChecker
4
+ from svlang.checkers.svengelska import SvengelskaChecker
5
+ from svlang.checkers.compound import CompoundSplitter
6
+ from svlang.checkers.lexicon import SwedishLexicon
7
+ from svlang.checkers.readability import LixCalculator
8
+
9
+ __all__ = ["ConsistencyChecker", "SvengelskaChecker", "CompoundSplitter", "SwedishLexicon", "LixCalculator"]
@@ -0,0 +1,167 @@
1
+ """Swedish compound word splitter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+
9
+ @dataclass
10
+ class CompoundSplit:
11
+ """Result of splitting a compound word."""
12
+ word: str
13
+ parts: list[str]
14
+ is_compound: bool
15
+
16
+
17
+ class CompoundSplitter:
18
+ """Split Swedish compound words into components.
19
+
20
+ Uses a dictionary-based approach: tries to find the longest prefix
21
+ that's a known word, then recursively splits the remainder.
22
+
23
+ Usage:
24
+ splitter = CompoundSplitter()
25
+ result = splitter.split("barnvagnshjul")
26
+ # → CompoundSplit(word="barnvagnshjul", parts=["barn", "vagn", "hjul"], is_compound=True)
27
+ """
28
+
29
+ # Common compound join letters (fogmorfem)
30
+ _JOINERS = ("s", "e", "o", "u", "")
31
+
32
+ def __init__(self, wordlist: set[str] | None = None):
33
+ if wordlist is not None:
34
+ self._words = wordlist
35
+ else:
36
+ self._words = self._load_default_wordlist()
37
+ self._min_part_len = 2
38
+
39
+ @staticmethod
40
+ def _load_default_wordlist() -> set[str]:
41
+ """Load a basic Swedish wordlist."""
42
+ wl_path = Path(__file__).parent.parent / "data" / "sv_wordlist.txt"
43
+ if wl_path.exists():
44
+ return {
45
+ line.strip().lower()
46
+ for line in wl_path.read_text(encoding="utf-8").splitlines()
47
+ if line.strip() and not line.startswith("#")
48
+ }
49
+ # Fallback: minimal built-in set of common Swedish words
50
+ return _BUILTIN_WORDS
51
+
52
+ def split(self, word: str) -> CompoundSplit:
53
+ """Try to split a compound word into parts."""
54
+ if not word or len(word) < 2:
55
+ return CompoundSplit(word=word, parts=[word] if word else [], is_compound=False)
56
+ word_lower = word.lower()
57
+ parts = self._try_split(word_lower)
58
+ if parts and len(parts) > 1:
59
+ return CompoundSplit(word=word, parts=parts, is_compound=True)
60
+ return CompoundSplit(word=word, parts=[word], is_compound=False)
61
+
62
+ def _try_split(self, word: str, depth: int = 0) -> list[str] | None:
63
+ """Recursive compound splitting."""
64
+ if depth > 5:
65
+ return None
66
+ if len(word) < self._min_part_len * 2:
67
+ if word in self._words:
68
+ return [word]
69
+ return None
70
+
71
+ # Try splitting at every position — longest prefix first
72
+ # This prefers "sjukhus+byggnad" over "sjuk+husbyggnad"
73
+ best: list[str] | None = None
74
+ for i in range(len(word) - self._min_part_len, self._min_part_len - 1, -1):
75
+ prefix = word[:i]
76
+ if prefix not in self._words:
77
+ continue
78
+
79
+ remainder = word[i:]
80
+
81
+ # Try with and without joiners
82
+ for joiner in self._JOINERS:
83
+ if joiner and remainder.startswith(joiner):
84
+ rest = remainder[len(joiner):]
85
+ else:
86
+ if joiner:
87
+ continue
88
+ rest = remainder
89
+
90
+ if not rest:
91
+ continue
92
+
93
+ # Is the rest a word?
94
+ if rest in self._words:
95
+ candidate = [prefix, rest]
96
+ # Prefer fewest parts, then longest first part
97
+ if best is None or len(candidate) < len(best):
98
+ best = candidate
99
+ continue
100
+
101
+ # Try splitting the rest recursively
102
+ sub = self._try_split(rest, depth + 1)
103
+ if sub:
104
+ candidate = [prefix] + sub
105
+ if best is None or len(candidate) < len(best):
106
+ best = candidate
107
+
108
+ # If we found a 2-part split with longest prefix, that's optimal
109
+ if best and len(best) == 2:
110
+ return best
111
+
112
+ return best
113
+
114
+ def is_valid_compound(self, word: str) -> bool:
115
+ """Check if a word is a valid compound."""
116
+ return self.split(word).is_compound
117
+
118
+
119
+ # Basic Swedish words for fallback (no external file needed)
120
+ _BUILTIN_WORDS = {
121
+ # Common nouns
122
+ "barn", "bil", "bok", "bord", "brev", "bro", "dag", "dator", "del",
123
+ "djur", "dörr", "fisk", "flyg", "folk", "fot", "färg", "förening",
124
+ "gata", "glas", "golv", "gård", "hand", "hem", "hjul", "hund", "hus",
125
+ "hår", "jord", "katt", "klass", "klocka", "konst", "kraft", "kropp",
126
+ "kung", "kvinna", "källa", "lag", "land", "ljus", "luft", "lägenhet",
127
+ "man", "mat", "mark", "mor", "musik", "natt", "namn", "nyckel",
128
+ "ord", "papper", "plats", "polis", "program", "rum", "rätt",
129
+ "sjö", "skog", "skola", "sol", "stad", "stol", "ström", "system",
130
+ "tak", "tid", "trafik", "trä", "vagn", "vakt", "vatten", "vin",
131
+ "vind", "väg", "vägg", "värld", "växt", "yta", "öga", "öra",
132
+ # Buildings & places
133
+ "bana", "bank", "butik", "fabrik", "hus", "kyrka", "plan",
134
+ "sjukhus", "station", "torget", "tunnel",
135
+ # Compound-common nouns
136
+ "boll", "brand", "bruk", "by", "båt", "flod", "flyg", "hamn",
137
+ "hyra", "is", "järn", "krig", "kust", "köp", "leda", "mot",
138
+ "park", "resa", "ring", "sand", "sjuk", "snö", "sång", "torg",
139
+ "tåg", "vapen", "vård",
140
+ # Sports & activities
141
+ "fotboll", "handboll", "ishockey", "tennis",
142
+ # Government & society
143
+ "riksdag", "kommun", "ledamot", "minister", "samhälle", "stat",
144
+ # Transport
145
+ "flyg", "järnväg", "spår", "tåg", "tunnel", "buss",
146
+ # Common adjectives
147
+ "stor", "liten", "ny", "gammal", "ung", "lång", "kort", "bred",
148
+ "hög", "låg", "varm", "kall", "vit", "svart", "röd", "blå", "grön",
149
+ "snabb", "sen", "fin", "ren", "fri",
150
+ # Common verbs (stem)
151
+ "lek", "spel", "skriv", "läs", "kör", "spring", "tänk", "sov",
152
+ "sjung", "flytt", "bygg", "städ", "lär", "säg",
153
+ # Body parts
154
+ "arm", "ben", "finger", "huvud", "mage", "rygg", "tand",
155
+ # Nature
156
+ "berg", "blad", "blomma", "eld", "frukt", "gren", "sten", "träd",
157
+ # House/building
158
+ "dörr", "fönster", "golv", "kök", "rum", "trapp", "vägg",
159
+ "byggnad", "våning",
160
+ # Tech
161
+ "data", "fil", "kod", "nät", "webb", "server", "skärm",
162
+ # More common compound parts (prefixes)
163
+ "arbets", "efter", "flyg", "folk", "fot", "före", "grupp", "halv",
164
+ "huvud", "inne", "järn", "lands", "mellan", "mitt", "natt", "riks",
165
+ "sam", "sjuk", "slut", "snö", "sol", "stats", "stor", "trafik",
166
+ "tunnel", "under", "ute", "över",
167
+ }
@@ -0,0 +1,75 @@
1
+ """Consistency checker — find same source translated differently."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+
8
+ @dataclass
9
+ class Inconsistency:
10
+ """A source string with multiple different translations."""
11
+ source: str
12
+ translations: dict[str, list[str]] # translation → list of locations
13
+
14
+
15
+ class ConsistencyChecker:
16
+ """Check that identical source strings have identical translations.
17
+
18
+ Usage:
19
+ checker = ConsistencyChecker()
20
+ checker.add("Save", "Spara", "file_menu.po:12")
21
+ checker.add("Save", "Lagra", "other.po:45")
22
+ issues = checker.check()
23
+ # → [Inconsistency(source="Save", translations={"Spara": [...], "Lagra": [...]})]
24
+ """
25
+
26
+ def __init__(self, *, case_sensitive: bool = True):
27
+ self._case_sensitive = case_sensitive
28
+ # source → {translation → [locations]}
29
+ self._entries: dict[str, dict[str, list[str]]] = {}
30
+
31
+ def _normalize(self, text: str) -> str:
32
+ if self._case_sensitive:
33
+ return text
34
+ return text.lower()
35
+
36
+ def add(self, source: str, translation: str, location: str = "") -> None:
37
+ """Register a source→translation pair."""
38
+ key = self._normalize(source)
39
+ if key not in self._entries:
40
+ self._entries[key] = {}
41
+ norm_trans = self._normalize(translation)
42
+ if norm_trans not in self._entries[key]:
43
+ self._entries[key][norm_trans] = []
44
+ self._entries[key][norm_trans].append(location)
45
+
46
+ def check(self) -> list[Inconsistency]:
47
+ """Return all source strings with inconsistent translations."""
48
+ issues = []
49
+ for source, translations in self._entries.items():
50
+ if len(translations) > 1:
51
+ issues.append(Inconsistency(source=source, translations=translations))
52
+ issues.sort(key=lambda i: i.source)
53
+ return issues
54
+
55
+ def add_po_file(self, path: str) -> None:
56
+ """Load entries from a .po file (requires polib)."""
57
+ import polib
58
+ po = polib.pofile(path)
59
+ for entry in po.translated_entries():
60
+ loc = f"{path}:{entry.linenum}" if hasattr(entry, 'linenum') else path
61
+ self.add(entry.msgid, entry.msgstr, loc)
62
+
63
+ def add_ts_file(self, path: str) -> None:
64
+ """Load entries from a Qt .ts file."""
65
+ import xml.etree.ElementTree as ET
66
+ tree = ET.parse(path)
67
+ for msg in tree.findall('.//message'):
68
+ src = msg.findtext('source', '')
69
+ trans = msg.findtext('translation', '')
70
+ if src and trans:
71
+ loc_elem = msg.find('location')
72
+ loc = f"{path}"
73
+ if loc_elem is not None:
74
+ loc = f"{loc_elem.get('filename', path)}:{loc_elem.get('line', '')}"
75
+ self.add(src, trans, loc)
@@ -0,0 +1,74 @@
1
+ """Swedish↔English dictionary lookup based on Folkets lexikon."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+
9
+ @dataclass
10
+ class LookupResult:
11
+ """A dictionary lookup result."""
12
+ word: str
13
+ translations: list[str]
14
+ found: bool
15
+
16
+
17
+ class SwedishLexicon:
18
+ """Swedish→English dictionary from Folkets lexikon (36k entries).
19
+
20
+ Usage:
21
+ lex = SwedishLexicon()
22
+ result = lex.lookup("hund")
23
+ # → LookupResult(word="hund", translations=["dog"], found=True)
24
+
25
+ results = lex.search("bil")
26
+ # → all words starting with "bil": bil, bildäck, bilkörning, ...
27
+ """
28
+
29
+ def __init__(self):
30
+ self._dict: dict[str, list[str]] = {}
31
+ self._load()
32
+
33
+ def _load(self):
34
+ tsv_path = Path(__file__).parent.parent / "data" / "folkets_sv_en.tsv"
35
+ if not tsv_path.exists():
36
+ return
37
+ for line in tsv_path.read_text(encoding="utf-8").splitlines():
38
+ if line.startswith("#") or "\t" not in line:
39
+ continue
40
+ sv, en = line.split("\t", 1)
41
+ self._dict[sv.strip()] = [t.strip() for t in en.split(",")]
42
+
43
+ def lookup(self, word: str) -> LookupResult:
44
+ """Look up a Swedish word and get English translations."""
45
+ key = word.lower().strip()
46
+ if key in self._dict:
47
+ return LookupResult(word=word, translations=self._dict[key], found=True)
48
+ return LookupResult(word=word, translations=[], found=False)
49
+
50
+ def search(self, prefix: str, limit: int = 20) -> list[LookupResult]:
51
+ """Find all words starting with prefix."""
52
+ prefix = prefix.lower().strip()
53
+ results = []
54
+ for sv, ens in self._dict.items():
55
+ if sv.startswith(prefix):
56
+ results.append(LookupResult(word=sv, translations=ens, found=True))
57
+ if len(results) >= limit:
58
+ break
59
+ return results
60
+
61
+ def reverse_lookup(self, english: str, limit: int = 20) -> list[LookupResult]:
62
+ """Find Swedish words that translate to a given English word."""
63
+ eng_lower = english.lower().strip()
64
+ results = []
65
+ for sv, ens in self._dict.items():
66
+ if any(eng_lower in e.lower() for e in ens):
67
+ results.append(LookupResult(word=sv, translations=ens, found=True))
68
+ if len(results) >= limit:
69
+ break
70
+ return results
71
+
72
+ @property
73
+ def size(self) -> int:
74
+ return len(self._dict)
@@ -0,0 +1,72 @@
1
+ """LIX readability index calculator for Swedish text."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+
8
+
9
+ @dataclass
10
+ class LixResult:
11
+ score: float
12
+ level: str
13
+ words: int
14
+ sentences: int
15
+ long_words: int
16
+
17
+
18
+ # Swedish abbreviations that contain periods but don't end sentences
19
+ _ABBREVS = re.compile(
20
+ r'\b(?:t\.ex|bl\.a|dvs|obs|osv|m\.fl|m\.m|s\.k|d\.v\.s|o\.s\.v|f\.d|t\.o\.m|s\.a\.s|ev|kl|nr|st|ca)\.',
21
+ re.IGNORECASE,
22
+ )
23
+
24
+ _SENTENCE_ENDINGS = re.compile(r'[.!?…]+')
25
+
26
+
27
+ class LixCalculator:
28
+ """Calculate the LIX readability index for Swedish text."""
29
+
30
+ def calculate(self, text: str) -> LixResult:
31
+ if not text or not text.strip():
32
+ return LixResult(score=0.0, level="Mycket lättläst", words=0, sentences=0, long_words=0)
33
+
34
+ # Replace abbreviations with placeholder (no period) to avoid false sentence breaks
35
+ cleaned = _ABBREVS.sub(lambda m: m.group(0).replace('.', '\x00'), text)
36
+
37
+ # Count sentences
38
+ sentences = len([s for s in _SENTENCE_ENDINGS.split(cleaned) if s.strip()])
39
+ if sentences == 0:
40
+ sentences = 1
41
+
42
+ # Extract words (sequences of word characters including Swedish chars)
43
+ word_list = re.findall(r'[a-zåäöéA-ZÅÄÖÉ\-]+', text)
44
+ word_count = len(word_list)
45
+
46
+ if word_count == 0:
47
+ return LixResult(score=0.0, level="Mycket lättläst", words=0, sentences=sentences, long_words=0)
48
+
49
+ long_words = sum(1 for w in word_list if len(w) > 6)
50
+
51
+ score = (word_count / sentences) + (long_words * 100 / word_count)
52
+
53
+ return LixResult(
54
+ score=round(score, 1),
55
+ level=self._classify(score),
56
+ words=word_count,
57
+ sentences=sentences,
58
+ long_words=long_words,
59
+ )
60
+
61
+ @staticmethod
62
+ def _classify(score: float) -> str:
63
+ if score < 25:
64
+ return "Mycket lättläst"
65
+ elif score < 35:
66
+ return "Lättläst"
67
+ elif score < 45:
68
+ return "Medelsvår"
69
+ elif score < 55:
70
+ return "Svår"
71
+ else:
72
+ return "Mycket svår"
@@ -0,0 +1,229 @@
1
+ """Svengelska detector — flag unnecessary anglicisms in Swedish text."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+
10
+ @dataclass
11
+ class Anglicism:
12
+ """A detected anglicism with a suggested Swedish alternative."""
13
+ word: str
14
+ suggestion: str
15
+ context: str # surrounding text
16
+ position: int # char offset
17
+
18
+
19
+ # Common anglicisms with Swedish alternatives.
20
+ # Based on Språkrådet recommendations and common translation pitfalls.
21
+ _ANGLICISMS: dict[str, str] = {
22
+ # Verbs
23
+ "implementera": "genomföra, införa",
24
+ "initiera": "inleda, starta",
25
+ "adressera": "ta itu med, hantera",
26
+ "facilitera": "underlätta",
27
+ "monitorera": "övervaka",
28
+ "trigga": "utlösa, sätta igång",
29
+ "briffa": "informera, instruera",
30
+ "mejla": "e-posta, skicka e-post",
31
+ "googla": "söka på nätet",
32
+ "cancelera": "avboka, ställa in",
33
+ "cancella": "avboka, ställa in",
34
+ "benchmarka": "jämföra, mäta",
35
+ "brainstorma": "idésamla",
36
+ "busta": "spränga, bryta",
37
+ "chilla": "koppla av, ta det lugnt",
38
+ "churna": "tappa kunder",
39
+ "converta": "omvandla, konvertera",
40
+ "delivera": "leverera",
41
+ "dippa": "doppa, sjunka",
42
+ "escalera": "eskalera, trappa upp",
43
+ "fetcha": "hämta",
44
+ "flusha": "spola, tömma",
45
+ "forwarda": "vidarebefordra",
46
+ "launcha": "lansera",
47
+ "lägga upp en story": "publicera",
48
+ "merga": "sammanfoga, slå ihop",
49
+ "pitcha": "presentera, sälja in",
50
+ "pusha": "driva på, trycka på",
51
+ "rendera": "återge, framställa",
52
+ "reseta": "återställa",
53
+ "reviewera": "granska",
54
+ "scrolla": "bläddra, rulla",
55
+ "skipa": "hoppa över",
56
+ "sparka av": "starta, dra igång",
57
+ "streama": "strömma, sända",
58
+ "swipa": "svepa",
59
+ "tagga": "märka, märka upp",
60
+ "trenda": "vara populär",
61
+ "uppdatera": None, # OK — established Swedish
62
+ "uppgradera": None, # OK — established
63
+
64
+ # Nouns
65
+ "approach": "tillvägagångssätt, metod",
66
+ "awareness": "medvetenhet, kännedom",
67
+ "backup": "säkerhetskopia",
68
+ "benchmark": "riktmärke, jämförelse",
69
+ "best practice": "bästa praxis, god praxis",
70
+ "blocker": "hinder",
71
+ "brainstorm": "idésamling",
72
+ "brief": "instruktion, uppdrag",
73
+ "budget": None, # OK — established
74
+ "case": "fall, ärende",
75
+ "challenge": "utmaning",
76
+ "deadline": "tidsfrist, slutdatum",
77
+ "feature": "funktion, egenskap",
78
+ "feedback": "återkoppling, respons",
79
+ "flow": "flöde",
80
+ "gap": "glapp, lucka",
81
+ "high-level": "övergripande",
82
+ "impact": "påverkan, inverkan",
83
+ "input": "synpunkter, underlag",
84
+ "insight": "insikt",
85
+ "issue": "fråga, problem",
86
+ "item": "punkt, sak",
87
+ "key takeaway": "viktigaste slutsatsen",
88
+ "leverage": "utnyttja, dra nytta av",
89
+ "mindset": "tankesätt, inställning",
90
+ "outcome": "resultat, utfall",
91
+ "output": "resultat, utdata",
92
+ "pain point": "smärtpunkt, problem",
93
+ "performance": "prestanda, resultat",
94
+ "pipeline": "kedja, process",
95
+ "pitch": "presentation, säljpitch",
96
+ "scope": "omfattning, räckvidd",
97
+ "setup": "uppställning, konfiguration",
98
+ "stakeholder": "intressent",
99
+ "startup": "nystartad, uppstart",
100
+ "target": "mål, målgrupp",
101
+ "task": "uppgift",
102
+ "team": None, # OK — established
103
+ "template": "mall",
104
+ "timeline": "tidslinje, tidsplan",
105
+ "tool": "verktyg",
106
+ "touchpoint": "kontaktpunkt",
107
+ "trade-off": "avvägning",
108
+ "trigger": "utlösare",
109
+ "update": "uppdatering",
110
+ "workshop": None, # OK — established
111
+
112
+ # Adjectives
113
+ "agil": "smidig, flexibel",
114
+ "aligned": "samstämd, i linje",
115
+ "customized": "anpassad, skräddarsydd",
116
+ "dedicated": "engagerad, tillägnad",
117
+ "hands-on": "praktisk, handgriplig",
118
+ "key": "viktig, central",
119
+ "lean": "resurssnål, slimmad",
120
+ "on track": "på rätt spår, i fas",
121
+ "proaktiv": "förebyggande, framåtblickande",
122
+ "senior": "erfaren, ledande",
123
+ "sustainable": "hållbar",
124
+ "transparent": None, # OK — established
125
+ }
126
+
127
+ # Filter out None (accepted words)
128
+ ANGLICISMS = {k: v for k, v in _ANGLICISMS.items() if v is not None}
129
+
130
+
131
+ class SvengelskaChecker:
132
+ """Detect unnecessary anglicisms in Swedish text.
133
+
134
+ Usage:
135
+ checker = SvengelskaChecker()
136
+ hits = checker.check("Vi behöver implementera en ny approach")
137
+ # → [Anglicism("implementera", "genomföra, införa", ...),
138
+ # Anglicism("approach", "tillvägagångssätt, metod", ...)]
139
+ """
140
+
141
+ # Swedish inflection suffixes to strip when matching
142
+ # Order matters: longest first
143
+ _SUFFIXES = (
144
+ "erade", "erades", # -era verbs past: implementerade
145
+ "ering", # noun from -era verb: implementering
146
+ "erna", "arna", "orna", # plural definite
147
+ "erar", # -era verbs present: implementerar
148
+ "erat", # -era verbs supine: implementerat
149
+ "ande", # present participle
150
+ "ades", # past passive
151
+ "ers", "ens", "ets", # genitive
152
+ "ade", # past tense
153
+ "ar", "er", "or", # plural
154
+ "en", "et", "an", # definite
155
+ "at", "ad", # supine / past participle
156
+ "s", # genitive / plural
157
+ )
158
+
159
+ def __init__(self, *, extra_terms: dict[str, str] | None = None):
160
+ self._terms = dict(ANGLICISMS)
161
+ if extra_terms:
162
+ self._terms.update(extra_terms)
163
+ # Build regex pattern — sort by length (longest first) for greedy match
164
+ escaped = [re.escape(t) for t in sorted(self._terms, key=len, reverse=True)]
165
+ self._pattern = re.compile(
166
+ r'\b(' + '|'.join(escaped) + r')\b',
167
+ re.IGNORECASE,
168
+ )
169
+ # Also build a set for fast stem lookup
170
+ self._term_set = {t.lower() for t in self._terms}
171
+
172
+ def _stem_match(self, word: str) -> str | None:
173
+ """Try to match a word to a known anglicism by stripping suffixes."""
174
+ low = word.lower()
175
+ if low in self._term_set:
176
+ return low
177
+ for suffix in self._SUFFIXES:
178
+ if low.endswith(suffix) and len(low) > len(suffix) + 2:
179
+ stem = low[:-len(suffix)]
180
+ if stem in self._term_set:
181
+ return stem
182
+ # Try adding back common verb ending: implementer → implementera
183
+ if (stem + "a") in self._term_set:
184
+ return stem + "a"
185
+ return None
186
+
187
+ def check(self, text: str) -> list[Anglicism]:
188
+ """Find anglicisms in text."""
189
+ hits = []
190
+ seen_positions: set[int] = set()
191
+
192
+ # First pass: exact pattern matches
193
+ for m in self._pattern.finditer(text):
194
+ word = m.group(0)
195
+ key = word.lower()
196
+ suggestion = self._terms.get(key, "")
197
+ if not suggestion:
198
+ suggestion = self._terms.get(word, "")
199
+ if suggestion:
200
+ start = max(0, m.start() - 30)
201
+ end = min(len(text), m.end() + 30)
202
+ context = text[start:end]
203
+ hits.append(Anglicism(
204
+ word=word, suggestion=suggestion,
205
+ context=context, position=m.start(),
206
+ ))
207
+ seen_positions.add(m.start())
208
+
209
+ # Second pass: check inflected forms (word boundaries)
210
+ for m in re.finditer(r'\b(\w+)\b', text):
211
+ if m.start() in seen_positions:
212
+ continue
213
+ stem = self._stem_match(m.group(0))
214
+ if stem:
215
+ suggestion = self._terms[stem]
216
+ start = max(0, m.start() - 30)
217
+ end = min(len(text), m.end() + 30)
218
+ context = text[start:end]
219
+ hits.append(Anglicism(
220
+ word=m.group(0), suggestion=suggestion,
221
+ context=context, position=m.start(),
222
+ ))
223
+
224
+ hits.sort(key=lambda h: h.position)
225
+ return hits
226
+
227
+ @property
228
+ def term_count(self) -> int:
229
+ return len(self._terms)