Zeyrek

Zeyrek is a Python morphological analyzer and lemmatizer for Turkish. It is a partial port of the Zemberek-NLP Tools (Morphology). Zeyrek can perform morphological analysis of Turkish text, returning all possible parses for each word, and lemmatize words, returning all possible base (non-inflected) forms of words.

Installation

pip install zeyrek

or, in a project managed with uv:

uv add zeyrek

Zeyrek supports Python 3.11 and later.

With CPython on Linux and macOS (x86-64 and ARM) and on Windows (x86-64), it also installs zeyrek-rs and analyzes in Rust, which is faster. Elsewhere it analyzes in Python, with the same results.

To install it without Rust:

pip install --no-deps zeyrek

or, in a uv project, add this to pyproject.toml:

[tool.uv]
exclude-dependencies = ["zeyrek-rs"]

With zeyrek-rs installed, MorphAnalyzer(pure_python=True) or the environment variable ZEYREK_PURE_PYTHON=1 makes the analyzer run in Python.

Usage

To use Zeyrek, first create an instance of MorphAnalyzer class:

>>> import zeyrek
>>> analyzer = zeyrek.MorphAnalyzer()

Then, you can call its analyze method on words or texts to get all possible analyses:

>>> for parse in analyzer.analyze("benim")[0]:
...     print(parse)
Parse(word='benim', lemma='ben', pos='Noun', morphemes=['Noun', 'A3sg', 'P1sg'], formatted='[ben:Noun] ben:Noun+A3sg+im:P1sg')
Parse(word='benim', lemma='ben', pos='Pron', morphemes=['Pron', 'A1sg', 'Gen'], formatted='[ben:Pron,Pers] ben:Pron+A1sg+im:Gen')
Parse(word='benim', lemma='ben', pos='Verb', morphemes=['Noun', 'A3sg', 'Zero', 'Verb', 'Pres', 'A1sg'], formatted='[ben:Noun] ben:Noun+A3sg|Zero→Verb+Pres+im:A1sg')
Parse(word='benim', lemma='ben', pos='Verb', morphemes=['Pron', 'A1sg', 'Zero', 'Verb', 'Pres', 'A1sg'], formatted='[ben:Pron,Pers] ben:Pron+A1sg|Zero→Verb+Pres+im:A1sg')

A word often has several analyses, and the right one depends on the sentence. disambiguate returns the most likely analysis of each word, chosen with Zemberek’s disambiguation model. The model looks at two words back, so a few rules correct it where Turkish needs more: a genitive earlier in the clause, a participle before a verb, and a lowercase word that isn’t a proper noun. kitabı is “the book” as an object in the first sentence, and “his book” in the second:

>>> for parse in analyzer.disambiguate("Bu kitabı okudum. Ali'nin kitabı masada."):
...     print(parse.formatted)
[bu:Det] bu:Det
[kitap:Noun] kitab:Noun+A3sg+ı:Acc
[okumak:Verb] oku:Verb+du:Past+m:A1sg
[.:Punc] .:Punc
[Ali:Noun,Prop] ali:Noun+A3sg+nin:Gen
[kitap:Noun] kitab:Noun+A3sg+ı:P3sg
[masa:Noun] masa:Noun+A3sg+da:Loc
[.:Punc] .:Punc

disambiguate returns one list for the whole text. analyze_sentences keeps the sentences apart, and gives the start and end of each sentence and word in the text. Each word has its most likely analysis in best and all its analyses in analyses:

>>> text = "Bu kitabı okudum. Ali'nin kitabı masada."
>>> for sentence in analyzer.analyze_sentences(text):
...     print(sentence.start, sentence.end, sentence.text)
...     for word in sentence.words:
...         print(
...             " ",
...             word.start,
...             word.end,
...             word.word,
...             word.best.morphemes,
...             len(word.analyses),
...         )
0 17 Bu kitabı okudum.
  0 2 Bu ['Det'] 2
  3 9 kitabı ['Noun', 'A3sg', 'Acc'] 4
  10 16 okudum ['Verb', 'Past', 'A1sg'] 1
  16 17 . ['Punc'] 1
18 40 Ali'nin kitabı masada.
  18 25 Ali'nin ['Noun', 'A3sg', 'Gen'] 2
  26 32 kitabı ['Noun', 'A3sg', 'P3sg'] 4
  33 39 masada ['Noun', 'A3sg', 'Loc'] 2
  39 40 . ['Punc'] 1

The text of a sentence or a word is text[start:end].

If you only need the base form of words, or lemmas, you can call lemmatize. It returns the lemma of the most likely analysis of each word:

>>> analyzer.lemmatize("Mektup onun tarafından yazıldı.")
['mektup', 'o', 'taraf', 'yazmak', '.']

To get every possible lemma, create the analyzer with return_all_lemmas=True. lemmatize then returns a list of tuples, with each word and a list of its possible lemmas:

>>> zeyrek.MorphAnalyzer(return_all_lemmas=True).lemmatize("benim")
[('benim', ['ben'])]

A lemma is the root of the word, and derivational suffixes can change its meaning a lot. derived_lemmas returns, for each analysis of a word, the lemmas from the root to the stem after the last derivational suffix. The last one is the word without its inflectional suffixes:

>>> analyzer.derived_lemmas("çekilişle")
[['çekiliş'], ['çekil', 'çekiliş'], ['çek', 'çekil', 'çekiliş']]

MorphAnalyzer keeps the analyses of the last 10,000 words it saw, so repeated words in a text are analyzed once. Set the size with cache_size, or turn the cache off with cache_size=0:

>>> analyzer = zeyrek.MorphAnalyzer(cache_size=50_000)

User Guide

The analyzer returns each analysis as a Parse, a named tuple with these fields:

  • word: the word as it was written.

  • lemma: the dictionary form of the word, such as yazmak for yazıldı.

  • pos: the part of speech of the word. A Turkish word can be made of several inflectional groups, each with its own part of speech: güzellik is the adjective güzel made a noun with -lik. pos is the part of speech of the last group.

  • morphemes: the short names of the word’s morphemes, such as ['Noun', 'A3pl', 'P1sg', 'Abl'].

  • formatted: the analysis as a string, written by the analyzer’s formatter. See Formatters.

Tags lists the parts of speech and morphemes, with an example of each.

A word that can’t be analyzed gets a single Parse with Unk in every field but word. lemmatize returns the word itself as its lemma:

>>> analyzer.analyze_word("xqz")
[Parse(word='xqz', lemma='Unk', pos='Unk', morphemes=['Unk'], formatted='Unk')]
>>> analyzer.lemmatize("xqz geldi")
['xqz', 'gelmek']

Adding words

add_dictionary adds the words of a text file to an analyzer. The file has a word on each line, in the format of Zemberek’s dictionaries. A word without attributes is a noun:

guglamak [P:Verb]
selfi
analyzer.add_dictionary("my-words.txt")
analyzer.analyze_word("gugladım")[0].formatted
# '[guglamak:Verb] gugla:Verb+dı:Past+m:A1sg'

Attributes go in brackets after the word, separated by semicolons:

  • P: is the part of speech, and the secondary one after a comma: [P:Verb], [P:Noun, Prop]. The tags are the same as in analyses.

  • A: lists the root’s attributes, separated by commas. The common ones are Voicing and NoVoicing for whether the last consonant softens before a vowel (kitap, kitabı), LastVowelDrop (ağız, ağzı), Doubling (hak, hakkı), and InverseHarmony for suffixes with front vowels after a back vowel (saat, saati). All of them are in zeyrek.attributes.RootAttribute.

  • Pr: is the pronunciation, which decides the vowels of the suffixes: [Pr:blendır] for blender.

  • Roots: gives the parts of a compound, with A:CompoundP3sg: [A:CompoundP3sg; Roots:göl-baş].

A word that is already in the dictionaries can be added again: its analyses aren’t repeated.

Words missing from the dictionaries are analyzed as Zemberek does: proper nouns and abbreviations written with an apostrophe, numbers, dates, clock times, percentages, Roman numerals, URLs, emails, hashtags and mentions.

>>> for word in ["Melik'in", "10:30'da", "%50'si", "XIX."]:
...     print(analyzer.analyze_word(word)[0].formatted)
[Melik:Noun,Prop] melik:Noun+A3sg+in:Gen
[10:30:Num,Clock] 10:30:Num|Zero→Noun+A3sg+da:Loc
[%50:Num,Percent] %50:Num|Zero→Noun+A3sg+si:P3sg
[XIX.:Num,RomanNumeral] XIX.:Num

Informal Turkish

Spoken Turkish, and texts written the way it sounds, shorten many suffixes: geliyom for geliyorum, yapcaz for yapacağız, yazak for yazalım. An analyzer created with informal=True analyzes these words as Zemberek does with useInformalAnalysis:

>>> informal_analyzer = zeyrek.MorphAnalyzer(informal=True)
>>> for word in ["geliyom", "yapcaz", "yazmıycam"]:
...     print(informal_analyzer.analyze_word(word)[0].formatted)
[gelmek:Verb] gel:Verb+iyo:Prog1_Informal+m:A1sg
[yapmak:Verb] yap:Verb+ca:Fut_Informal+z:A1pl
[yazmak:Verb] yaz:Verb+mı:Neg_Informal+yca:Fut_Informal+m:A1sg

The shortened suffixes get their own morphemes, such as Prog1_Informal for Prog1. They are listed in Tags. The UD formatter writes them with the features of the formal morphemes.

to_formal converts each analysis of an informal word to the formal word, as Zemberek’s InformalAnalysisConverter does. Each informal morpheme is replaced by the formal one it stands for, and the analysis’s dictionary item generates the word from them. It returns one item for each analysis that analyze_word returns, in the same order:

>>> for parse in informal_analyzer.to_formal("gidicem"):
...     print(parse.word, parse.formatted)
gideceğim [gitmek:Verb] gid:Verb+eceğ:Fut+im:A1sg
gidicem [gidi:Adj] gidi:Adj|ce:AsIf→Adj|Zero→Noun+A3sg+m:P1sg

An analysis without informal morphemes, like the second one, keeps its parse, with the word as it was written. A converted word is written as generate writes it, in lowercase and without an apostrophe, as Zemberek’s converter writes it, so to_formal("Gidicem") gives gideceğim and Gidicem. An analysis whose formal morphemes make no word is None, where Zemberek’s converter returns null. The formal morphemes of gidiceğim read as “I am the one who will go”, Verb|FutPart→Noun+A3sg|Zero→Verb+Pres+A1sg, make no word, so that analysis is None. An analyzer made without informal=True gives no word informal morphemes, so its to_formal returns the analyses of analyze_word unchanged.

Some formal words get informal analyses too: ancak, “but”, can also be an-cak, “will remember”. Use informal=True for texts that need it, so that formal texts don’t get the extra analyses.

Words without Turkish letters

Text typed on a keyboard without Turkish letters writes çocuk as cocuk and ışık as isik. ignore_diacritics=True analyzes each letter as itself or as the same letter with or without its marks, as Zemberek’s ignoreDiacriticsInAnalysis does. The analyses are of the words with Turkish letters:

>>> ascii_analyzer = zeyrek.MorphAnalyzer(ignore_diacritics=True)
>>> ascii_analyzer.analyze_word("ogretmenlerimizden")[0].formatted
'[öğretmen:Noun] öğretmen:Noun+ler:A3pl+imiz:P1pl+den:Abl'
>>> ascii_analyzer.lemmatize("Cocuklar agaca tirmandi.")
['çocuk', 'ağaç', 'tırmanmak', '.']

A word gets the analyses of every word it can be read as, so isik is both ışık and the name Işık, and analysis is about twice as slow.

To get the text itself with its Turkish letters back, use deasciify, a port of Zemberek’s Deasciifier. It decides each c, g, i, o, s and u from the letters around it, with a table of patterns learned from a corpus:

>>> from zeyrek.deasciifier import deasciify
>>> deasciify("Ogretmenlerimizden ogrendiklerimizi unutmayacagiz.")
'Öğretmenlerimizden öğrendiklerimizi unutmayacağız.'

It doesn’t use a dictionary, so it is fast, but it can get a word wrong. On 21,000 words of news text, it restored 98.6% of them. It leaves Isik sondu as Isik söndü, for one.

LatticeDeasciifier, Zemberek’s newer deasciifier, restores whole words. Each word’s spellings come from its analyses, informal ones included, and from the spellings a corpus has for it, and the words around it choose one. A word the dictionaries don’t have gets the spelling a model of letters and vowel harmony finds most likely. It’s slower, and gets more words right:

>>> from zeyrek import CircumflexMode, LatticeDeasciifier
>>> deasciifier = LatticeDeasciifier()
>>> deasciifier.deasciify("Isik sondu, hala gelmedi.")
'Işık söndü, hâlâ gelmedi.'
>>> deasciifier.deasciify("Isik sondu, hala gelmedi.", CircumflexMode.NONE)
'Işık söndü, hala gelmedi.'

It writes only the circumflexes that tell words apart, as in hâlâ, still, and hala, aunt. CircumflexMode.NONE writes none and CircumflexMode.FULL writes all the dictionaries and the corpus have. deasciify_known_words leaves the words the dictionaries don’t have as they are, for a spell checker to correct. URLs, e-mail addresses, mentions, and words with digits and no apostrophe keep their letters.

Formatters

A formatter turns an analysis into the formatted string of a Parse. Zeyrek has Zemberek’s formats and Universal Dependencies features for programs to read, and three formatters that write analyses in grammar terms for people.

Default formatter

The default formatter writes the analysis the way Zemberek does:

>>> analyzer.analyze_word("kitaplarımdan")[0].formatted
'[kitap:Noun] kitap:Noun+lar:A3pl+ım:P1sg+dan:Abl'
  • [kitap:Noun] is the dictionary item: its lemma and part of speech. A secondary part of speech follows a comma, as in [ben:Pron,Pers] or [Ankara:Noun,Prop].

  • kitap:Noun is the stem of the word, then its first morpheme.

  • +lar:A3pl is the next morpheme. The letters it adds to the word come before the colon, and a morpheme that adds no letters, such as A3sg, has no colon.

  • | starts a new inflectional group, and → follows the derivational morpheme that changes the part of speech. In güzeldi, the adjective becomes a verb:

>>> analyzer.analyze_word("güzeldi")[0].formatted
'[güzel:Adj] güzel:Adj|Zero→Verb+di:Past+A3sg'

To leave out the letters of each morpheme, use a DefaultFormatter with add_surface=False:

>>> from zeyrek.formatters import DefaultFormatter
>>> analyzer.formatter = DefaultFormatter(add_surface=False)
>>> analyzer.analyze_word("kitaplarımdan")[0].formatted
'[kitap:Noun] Noun+A3pl+P1sg+Abl'

Zemberek’s other formats

Zemberek has other formats in AnalysisFormatters, and MorphAnalyzer takes them by name. Here they are for kitabımızdaymış, “it was apparently in our book”:

Name

Formatter

kitabımızdaymış

"lexical"

DefaultFormatter(add_surface=False)

[kitap:Noun] Noun+A3sg+P1pl+Loc|Zero→Verb+Narr+A3sg

"morphemes"

MorphemesFormatter(add_surface=False)

Noun+A3sg+P1pl+Loc|Zero→Verb+Narr+A3sg

"oflazer"

OflazerFormatter()

kitab+Noun+A3sg+P1pl+Loc^DB+Verb+Zero+Narr+A3sg

"sequence"

SequenceFormatter()

kitab:Noun + A3sg + ımız:P1pl + da:Loc + Zero + Verb + ymış:Narr + A3sg

"lexical_sequence"

SequenceFormatter(add_surface=False)

Noun + A3sg + P1pl + Loc + Zero + Verb + Narr + A3sg

"surface_sequence"

SequenceFormatter(add_morphemes=False)

kitab ımız da ymış

"stem_ending"

StemEndingFormatter()

kitab-ımızdaymış

The Oflazer style is close to the output of Kemal Oflazer’s analyzer. ^DB marks a derivation, and the new part of speech comes before the morpheme that derives it. The morphemes are Zemberek’s, so there is no Pnon or Nom:

>>> oflazer = zeyrek.MorphAnalyzer(formatter="oflazer")
>>> oflazer.analyze_word("kitaplardaymış")[0].formatted
'kitap+Noun+A3pl+Loc^DB+Verb+Zero+Narr+A3sg'

"stem_ending" splits the word into its stem, as it is written in the word, and the rest:

>>> stem_ending = zeyrek.MorphAnalyzer(formatter="stem_ending")
>>> stem_ending.analyze_word("kitabımdaki")[0].formatted
'kitab-ımdaki'

Universal Dependencies formatter

formatter="UD" writes the features of the word as Universal Dependencies features, the format of the Turkish UD treebanks:

>>> ud_analyzer = zeyrek.MorphAnalyzer(formatter="UD")
>>> ud_analyzer.analyze_word("kitaplarımdan")[0].formatted
'Case=Abl|Number=Plur|Number[psor]=Sing|Person=3|Person[psor]=1'
>>> ud_analyzer.analyze_word("geliyorum")[0].formatted
'Aspect=Prog|Mood=Ind|Number=Sing|Person=1|Polarity=Pos|Polite=Infm|Tense=Pres'
>>> ud_analyzer.analyze_word("okuyacakmışsın")[0].formatted
'Aspect=Perf|Evident=Nfh|Mood=Ind|Number=Sing|Person=2|Polarity=Pos|Tense=Fut'
>>> ud_analyzer.analyze_word("üç")[0].formatted
'NumType=Card'

A word gets the features of the part of speech it ends in. evdeyim, “I am at home”, is a noun that becomes a verb, so it gets the features of a verb and keeps the case of the noun:

>>> ud_analyzer.analyze_word("evdeyim")[0].formatted
'Aspect=Perf|Case=Loc|Mood=Ind|Number=Sing|Person=1|Polarity=Pos|Tense=Pres'

A derivational suffix makes a new word with its own case. In evdekiler, “the ones at home”, the locative belongs to evde, and the word after -ki is in the nominative. Each analysis has its own features:

>>> for parse in ud_analyzer.analyze_word("evdekiler"):
...     print(parse.pos, parse.formatted)
Verb Aspect=Perf|Mood=Ind|Number=Plur|Person=3|Polarity=Pos|Tense=Pres
Noun Case=Nom|Number=Plur|Person=3

The UD formatter writes features for nouns, verbs, pronouns, numerals and adjectives. Other parts of speech, such as conjunctions, are written in the default format:

>>> ud_analyzer.analyze_word("ve")[0].formatted
'[ve:Conj] ve:Conj'

CoNLL-U, Apertium and UniMorph

Three formatters write the formats of other tools, as Zemberek’s ConlluFormatter, ApertiumFormatter and UniMorphFormatter do. Each gets its name in MorphAnalyzer:

Name

Formatter

kitaplarımızdan

"conllu"

ConlluFormatter()

kitap\tNOUN\t_\tCase=Abl|Number=Plur|Number[psor]=Plur|Person=3|Person[psor]=1

"apertium"

ApertiumFormatter()

kitap<n><pl><px1pl><abl>

"unimorph"

UniMorphFormatter()

kitap\tkitaplarımızdan\tN;ABL;PL;PSS1P

"conllu" writes the LEMMA, UPOS, XPOS and FEATS columns of CoNLL-U, separated by tabs. Unlike the UD formatter’s features, they follow the annotation of a Turkish UD treebank: UD Turkish BOUN by default, or UD Turkish IMST with ConlluFormatter("imst"), which has Mood=Ind on verbs and calls var and yok adjectives:

>>> from zeyrek.formatters import ConlluFormatter
>>> analyzer.formatter = ConlluFormatter()
>>> analyzer.analyze_word("gidiyor")[0].formatted
'git\tVERB\t_\tAspect=Prog|Number=Sing|Person=3|Polarity=Pos|Tense=Pres'
>>> analyzer.formatter = ConlluFormatter("imst")
>>> analyzer.analyze_word("gidiyor")[0].formatted
'git\tVERB\tVerb\tAspect=Prog|Mood=Ind|Number=Sing|Person=3|Polarity=Pos|Tense=Pres'

"apertium" writes the tags of Apertium’s Turkic analyzers, such as apertium-tur. Verbs are <v>, without <tv> or <iv>, since the dictionaries don’t say whether a verb is transitive.

"unimorph" writes the lemma, the word and its UniMorph features. UniMorphFormatter(add_lemma_and_surface=False) writes only the features:

>>> from zeyrek.formatters import UniMorphFormatter
>>> analyzer.formatter = UniMorphFormatter(add_lemma_and_surface=False)
>>> analyzer.analyze_word("gidiyor")[0].formatted
'V;IND;PRS;PROG;3;SG;POS;DECL'

These formatters write a word at a time, so CoNLL-U’s other columns and its multiword tokens, such as İstanbul'daydı split into İstanbul'da and ydı, are left to the program that writes the sentence.

Oflazer’s tags and segmented words

"oflazer_strict" writes an analysis as Kemal Oflazer’s analyzer and the treebanks that use its tags do, as Zemberek’s OflazerFormatter does. Unlike "oflazer", it starts with the lemma, writes Pnon and Nom on nouns without a possessive or a case suffix and Pos on verbs that aren’t negative, and writes Unable as ^DB+Verb+Able+Neg:

>>> from zeyrek.formatters import StrictOflazerFormatter
>>> analyzer.formatter = StrictOflazerFormatter()
>>> analyzer.analyze_word("kitabımız")[0].formatted
'kitap+Noun+A3sg+P1pl+Nom'
>>> analyzer.analyze_word("gelemedi")[0].formatted
'gel+Verb^DB+Verb+Able+Neg+Past+A3sg'

StrictOflazerFormatter takes the tagset to write:

Dialect

Tagset

geliyordu

"metu_sabanci"

The METU-Sabancı treebank, the default

gel+Verb+Pos+Prog1^DB+Verb+Zero+Past+A3sg

"oflazer94"

Oflazer’s analyzer of 1994, with Adverb for Adv, PastPart for NarrPart and PresPart for AorPart

gel+Verb+Pos+Prog1^DB+Verb+Zero+Past+A3sg

"sak2008"

Haşim Sak’s analyzer, which doesn’t split a second tense off the verb

gel+Verb+Pos+Prog1+Past+A3sg

"starlang"

Starlang and KeNet, with the tags in capital letters

gel+VERB+POS+PROG1+PAST+A3SG

>>> analyzer.formatter = StrictOflazerFormatter("starlang")
>>> analyzer.analyze_word("geliyordu")[0].formatted
'gel+VERB+POS+PROG1+PAST+A3SG'

"canonical_surface_sequence" writes the lemma and the letters of each suffix, as Zemberek’s SegmentedSurfaceFormatter does. The root is written as its lemma has it, without the sound changes of the word, so every form of a word starts with the same letters, where "surface_sequence" writes kitab ımız dan. SegmentedFormatter(" + ") puts + between the parts:

>>> from zeyrek.formatters import SegmentedFormatter
>>> analyzer.formatter = SegmentedFormatter()
>>> analyzer.analyze_word("kitabımızdan")[0].formatted
'kitap ımız dan'
>>> analyzer.formatter = SegmentedFormatter(" + ")
>>> analyzer.analyze_word("gidiyor")[0].formatted
'git + iyor'

Writing your own formatter

A formatter is a subclass of zeyrek.formatters.Formatter with a format method that takes an analysis and returns a string. The analysis has the dictionary item in dict_item, the stem in stem, and the morphemes with their surfaces in morphemes:

>>> from zeyrek.formatters import Formatter
>>> class MorphemeIds(Formatter):
...     def format(self, analysis):
...         return " ".join(morpheme.id_ for morpheme, _ in analysis.morphemes)
>>> analyzer.formatter = MorphemeIds()
>>> analyzer.analyze_word("kitaplarımdan")[0].formatted
'Noun A3pl P1sg Abl'

Tokenization

analyze and lemmatize split a text into words with a port of Zemberek’s tokenizer, which you can also use on its own. It keeps together what belongs together in Turkish texts: suffixes after an apostrophe, abbreviations, ordinals, times, URLs and emoji. Each token has a type:

>>> from zeyrek.tokenization import sentences, tokenize
>>> [
...     (token.text, token.type.value)
...     for token in tokenize("H.T.'nin 2. kitabı 10:30'da çıktı :)")
... ]
[("H.T.'nin", 'AbbreviationWithDots'), ('2.', 'Number'), ('kitabı', 'Word'), ("10:30'da", 'Time'), ('çıktı', 'Word'), (':)', 'Emoticon')]

tokenize(text, keep_spaces=True) also returns the spaces and line breaks. The token types are in zeyrek.tokenization.TokenType.

detokenize joins tokens back into text, spaced as Turkish is written. Tokens from tokenize(text, keep_spaces=True) are joined as they are.

>>> from zeyrek.tokenization import detokenize
>>> detokenize(["«", "Çalıkuşu", "»", "'", "nu", "25", "°", "C'de", "okudum", "."])
"«Çalıkuşu»'nu 25°C'de okudum."

sentences splits a text into sentences with Zemberek’s sentence boundary model. A dot after an abbreviation or in a time doesn’t end a sentence:

>>> sentences("Prof. Dr. Ali geldi. Saat 10.30'da gitti!")
['Prof. Dr. Ali geldi.', "Saat 10.30'da gitti!"]

sentence_spans returns where each sentence starts and ends in the text instead:

>>> from zeyrek.tokenization import sentence_spans
>>> sentence_spans("Ali geldi. Veli gitti!")
[(0, 10), (11, 22)]

Spell checking

SpellChecker checks whether a word is spelled right, and suggests words one edit away from a misspelling: one letter deleted, added or replaced, or two letters next to each other swapped. A word is spelled right when one of its analyses, written in the word’s case, is the word itself, so a proper noun needs its capital letter and its apostrophe:

>>> checker = zeyrek.SpellChecker(analyzer)
>>> checker.check("çocuklarımızın"), checker.check("Ankara'dan"), checker.check("ankaradan")
(True, True, False)
>>> checker.suggest("öğretmenlerimizdn")
['öğretmenlerimizin', 'öğretmenlerimizden', 'öğretmenlerimizde', 'öğretmenlerimizdi']
>>> checker.suggest("ankaradan")[:3]
["Ankara'dan", "Ankara'da", 'anakaradan']

The suggestions are words the analyzer accepts. They are ranked by how often they appear in Zemberek’s corpus and by how far they are from the misspelling, and a letter that differs only in its marks, like ı for i, counts as less than a whole edit.

suggest_in_context ranks the same suggestions by the words around the misspelling, with Zemberek’s bigram model: how often each suggestion follows the word before it and precedes the word after it. None stands for the start or the end of a sentence:

>>> checker.suggest("adm")[:3]
['adam', 'adı', 'adım']
>>> checker.suggest_in_context("adm", "benim", None)[:3]
['adım', 'adam', 'adı']
>>> checker.suggest_in_context("kr", None, "yağıyor")[:3]
['kar', 'ki', 'kur']

A SpellChecker takes under a second to create and about 100 MB of memory once it has made suggestions, and 20 MB more once it has ranked them in context (35 MB without zeyrek-rs), so create one and reuse it.

Syllables and hyphenation

zeyrek.hyphenation splits words into syllables and finds where to hyphenate them, as Zemberek’s TurkishSyllableExtractor and TurkishHyphenator do:

>>> from zeyrek.hyphenation import split_index, syllable_boundaries, syllables
>>> syllables("öğretmenlerimizden")
['öğ', 'ret', 'men', 'le', 'ri', 'miz', 'den']
>>> syllable_boundaries("merhaba")
[0, 3, 5]

split_index(word, space) is where to break a word at the end of a line with space characters left, leaving one for the hyphen. It is the length of the word if the word fits, and -1 if not even its first syllable does, or if the word has no syllables:

>>> word = "merhaba"
>>> split_index(word, 6), split_index(word, 4), split_index(word, 3), split_index(word, 7)
(5, 3, -1, 7)

Loanwords that don’t follow the rules of Turkish syllables, such as tren, and words without a vowel get no syllables, and can’t be hyphenated. Anything that isn’t a vowel counts as a consonant, so punctuation stays with the letters next to it. With strict=True, as in Zemberek’s STRICT mode, a syllable can’t end in two consonants either:

>>> syllables("tren"), syllables("kitap."), syllables("Ankara'da")
([], ['ki', 'tap.'], ['An', 'ka', "ra'", 'da'])
>>> syllables("türkçe"), syllables("türkçe", strict=True)
(['türk', 'çe'], [])

Language identification

LanguageIdentifier is a port of Zemberek’s language identifier. Each language has a model of its three-letter sequences, and the language whose model gives the text’s sequences the highest probability wins. Its models are Zemberek’s tr_group models: Turkish, Azerbaijani, German, English, Kurdish, Kyrgyz, Uzbek, and unk for the other languages together. They don’t come with zeyrek, to keep it small; install them with the langid extra:

pip install "zeyrek[langid]"
>>> from zeyrek.langid import LanguageIdentifier
>>> identifier = LanguageIdentifier()
>>> identifier.identify("Merhaba dünya ve tüm gezegenler.")
'tr'
>>> identifier.identify("Bonjour le monde et toutes les planètes.")
'unk'

For long texts, identify(text, max_sample_count=50) scores only 50 sequences spread over the text, and identify_fast drops the lower-scoring models every 20 sequences. contains_language checks whether any slice of a text is in a language:

>>> text = "merhaba dünya ve tüm gezegenler Hola mundo y todos los planetas"
>>> identifier.contains_language(text, "tr", slice_size=20)
True

Zemberek also has models of 61 languages, 5.6 MB together, which the extra doesn’t install. To use them, download the lang-id/src/main/resources/models/compressed folder of Zemberek and pass its path: LanguageIdentifier("path/to/compressed"). These models have no unk model, so unk only comes back for a text too short to identify.

Numbers

zeyrek.numbers writes numbers in Turkish words and reads them back, as Zemberek’s TurkishNumbers does:

>>> from zeyrek import numbers
>>> numbers.to_words(1_234_567)
'bir milyon iki yüz otuz dört bin beş yüz altmış yedi'
>>> numbers.ordinal_to_words("101.")
'yüz birinci'
>>> numbers.to_number("iki bin üç yüz kırk beş")
2345
>>> numbers.separate_connected_numbers("onikibin")
['on', 'iki', 'bin']

to_number returns -1 for words that aren’t a number, or don’t make one as Turkish writes it, such as “bir bin”. The functions read numbers up to 999,999,999,999,999,999, as Zemberek does. digits_to_words reads each leading zero, as in a phone number: "007" is 'sıfır sıfır yedi'. ordinal_to_words raises ValueError for a number that ends in “milyon”, since Zemberek’s table has no ordinal for it.

Normalizing noisy text

SentenceNormalizer rewrites a noisy sentence, as people type in messages and on social media, in standard Turkish. It is a port of Zemberek’s TurkishSentenceNormalizer, and gives the same sentences, except where zeyrek’s analyzer reads a word differently, as Zeyrek and Zemberek describes. It restores Turkish letters, corrects typos, turns informal and shorthand words into formal ones, splits words written together and joins words written apart, and fixes the casing and the apostrophes of proper nouns and numbers:

>>> normalizer = zeyrek.SentenceNormalizer()
>>> normalizer.normalize("Tmm, yarin havuza giricem ve aksama kadar yaticam :)")
'Tamam, yarın havuza gireceğim ve akşama kadar yatacağım :)'
>>> normalizer.normalize("yarın bende gelicem ama saat 7 de orda olurmusun bilmiyom")
"yarın ben de geleceğim ama saat 7'de orada olur musun bilmiyorum"
>>> normalizer.normalize("urun harika. cok begendim.")
'Ürün harika. Çok beğendim.'

Each word gets candidates from the analyzer, the deasciifier, the spell checker, and the rewrites, splits and merges Zemberek learned from a corpus of noisy and clean sentences. A model trained on that corpus chooses one candidate for each word, with the words around it. Emoji, emoticons, URLs and mentions stay as they are, and a word that is right already stays too.

It reads about 8 MB of models and builds analyzers of its own the first time it normalizes a sentence. With zeyrek-rs, that takes about half a second and 320 MB of memory, and then a sentence takes 1 to 2 ms. Without it, it takes about 5 seconds and 350 MB, and a sentence takes about 30 ms. Every SentenceNormalizer shares them, so creating more than one costs nothing.

Generating words

generate_from_item goes the other way from analysis: it builds a word from a dictionary item and a list of morphemes, as Zemberek’s WordGenerator does. The item is named by its id, as in Zemberek, such as kitap_Noun or avuç_Noun_1, and the morphemes by their names in Parse.morphemes. Morphemes without letters, such as A3sg, Pnon and Nom, can be left out. Each result is a Parse whose word is the generated word:

>>> analyzer = zeyrek.MorphAnalyzer()
>>> analyzer.generate_from_item("kitap_Noun", ["A3pl", "P1sg", "Abl"])[0]
Parse(word='kitaplarımdan', lemma='kitap', pos='Noun', morphemes=['Noun', 'A3pl', 'P1sg', 'Abl'], formatted='[kitap:Noun] kitap:Noun+lar:A3pl+ım:P1sg+dan:Abl')
>>> [
...     parse.word
...     for parse in analyzer.generate_from_item("okumak_Verb", ["Neg", "Prog1", "A1pl"])
... ]
['okumuyoruz']
>>> [parse.word for parse in analyzer.generate_from_item("çocuk_Noun", ["Dim", "P1sg"])]
['çocukçuğum', 'çocukcağızım']

generate starts from a stem instead, and tries every stem the string starts with, so elma also gives the words of el:

>>> [parse.word for parse in analyzer.generate("elma", ["A3pl", "P1pl"])]
['ellerimiz', 'elmalarımız']

A suffix with letters is only added when the list names its morpheme, so ev with ["Rel"] makes nothing: “evdeki” needs ["Loc", "Rel"]. A morpheme the analyzer doesn’t know, or an item id the lexicon doesn’t have, raises ValueError. The suffixes of informal Turkish, such as Prog1_Informal, need informal=True.

Analyses in grammar terms

formatter="leipzig", "turkish" or "russian" writes each analysis in the terms of a grammar tradition, for people to read. Morphemes with no letters that the tradition leaves out, such as the nominative or the third person singular, are not written.

"leipzig" follows the Leipzig Glossing Rules. The first line splits the word into morphemes, and the second glosses each of them. The stem keeps its Turkish lemma, since the dictionary has no English translations. Where the rules have no abbreviation, the gloss is one common in glossed Turkish examples, such as AOR, EVID, ABIL, NEC and EQU.

>>> analyzer = zeyrek.MorphAnalyzer(formatter="leipzig")
>>> print(analyzer.analyze_word("kitaplarımdan")[0].formatted)
kitap-lar-ım-dan
kitap-PL-1SG.POSS-ABL
>>> print(analyzer.analyze_word("güzeldi")[0].formatted)
güzel-di
güzel-PST

"turkish" uses the terms of Turkish school grammar and the Türk Dil Kurumu, and "russian" the terms of Russian Turkology, after A. N. Kononov’s «Грамматика современного турецкого литературного языка» and I. V. Shcheka’s «Практическая грамматика турецкого языка». An arrow shows a new part of speech:

>>> for parse in zeyrek.MorphAnalyzer(formatter="turkish").analyze_word("evdekiler"):
...     print(parse.formatted)
ev (isim) + -de bulunma hâli eki + -ki aitlik eki → sıfat + ek-fiil + -ler 3. çoğul kişi eki
ev (isim) + -de bulunma hâli eki + -ki aitlik eki → sıfat → isim + -ler çokluk eki
>>> zeyrek.MorphAnalyzer(formatter="russian").analyze_word("kitaplarımdan")[0].formatted
'kitap (сущ.) + -lar аффикс мн. ч. + -ım аффикс принадлежности 1 л. ед. ч. + -dan исходный падеж'

To change the style of an analyzer you have, set its formatter:

>>> from zeyrek.formatters import ReadableFormatter
>>> analyzer.formatter = ReadableFormatter("russian")

Dependency parsing

DependencyParser finds the syntactic head of each word of a sentence, and the word’s Universal Dependencies relation to it, with the model of Zemberek’s dependency parser. It was trained on the UD_Turkish-BOUN treebank, and Zemberek reports 80.5% of heads and 73.3% of heads with relations right on its test set.

The model, 4.2 MB, comes in a package of its own, which the dependency extra installs:

pip install "zeyrek[dependency]"

Without it, DependencyParser() raises ImportError, and DependencyParser(model=path) reads a model file in Zemberek’s format from path.

>>> parser = zeyrek.DependencyParser()
>>> tree = parser.parse("Küçük sarı kuş yavaşça penceremin kenarına kondu.")
>>> for node in tree:
...     print(node.id, node.form, node.upos, node.head, node.deprel)
1 Küçük ADJ 3 amod
2 sarı ADJ 1 compound:redup
3 kuş NOUN 7 nsubj
4 yavaşça ADV 7 advmod
5 penceremin NOUN 6 nmod:poss
6 kenarına NOUN 7 obl
7 kondu VERB 0 root
8 . PUNCT 7 punct

The parser analyzes the sentence with a MorphAnalyzer, which it makes or takes as DependencyParser(analyzer), and makes the Universal Dependencies words from the most likely analysis of each word, with their lemma, part of speech and features, as Zemberek does. A word that ends in a copula or in “-ki” is two of these words, which CoNLL-U writes as a multiword token. to_conllu writes the tree in CoNLL-U, the format of the treebanks:

>>> tree = parser.parse("Evdeki çocuklar İstanbul'daydı.")
>>> print(tree.to_conllu())
# text = Evdeki çocuklar İstanbul'daydı.
1-2	Evdeki	_	_	_	_	_	_	_	_
1	Evde	ev	NOUN	_	Case=Loc|Number=Sing|Person=3	3	nmod	_	_
2	ki	ki	PART	Attr	_	1	dep:der	_	_
3	çocuklar	çocuk	NOUN	_	Case=Nom|Number=Plur|Person=3	4	nsubj	_	_
4-5	İstanbul'daydı	_	_	_	_	_	_	_	SpaceAfter=No
4	İstanbul'da	İstanbul	PROPN	_	Case=Loc|Number=Sing|Person=3	0	root	_	_
5	ydı	i	AUX	Zero	Aspect=Perf|Evident=Fh|Number=Sing|Person=3|Polarity=Pos|Tense=Past	4	cop	_	_
6	.	.	PUNCT	Punc	_	4	punct	_	_

parse_conllu parses sentences that are already Universal Dependencies words in CoNLL-U, such as a treebank’s, from their forms, lemmas, parts of speech and features.

The first parser created reads the model, and parsers share it. With zeyrek-rs, a parser parses about 100 sentences a second. In Python, without zeyrek-rs or with MorphAnalyzer(pure_python=True), it gives the same trees on Zemberek’s test sentences, but parses only a few sentences a second.

Differences from Zemberek

Zeyrek gives the same analyses as Zemberek 0.21.0 for almost every word. Its disambiguator adds a few rules to Zemberek’s model, its dictionaries add a few words, and it reads numbers such as 1.000 as cardinals. Zeyrek and Zemberek lists every difference, with example sentences, and says which answer the annotated corpora support.

Limitations

Zeyrek is in alpha, and its API can still change. It ports Zemberek’s morphological analysis, disambiguation, tokenization and detokenization, spell checking, word generation, deasciification, the conversion of informal words to formal ones, the normalization of noisy text, syllables and hyphenation, number words, language identification and dependency parsing. Zemberek’s other tools, such as named entity recognition and text classification, aren’t ported.

API reference

The API reference lists the methods of the analyzer, the spell checker, the dependency parser, the language identifier and the normalizer, the functions for tokenizing, restoring Turkish letters, syllables and numbers, and the formatter classes, with their arguments.

Changelog

The changes in each version are in the GitHub releases.

License

Licensed under MIT License. Zemberek, from parts of which Zeyrek was ported, is under Apache License, Version 2.0. Zeyrek’s dictionaries, disambiguation model and dependency parser model come from Zemberek, and LICENSE-zemberek in the repository has Zemberek’s license. The dependency parser model’s package, zeyrek-dependency-model, has its own license and provenance note.