obulat/zeyrek
Tentang
Python morphological analyzer for Turkish language. Partial port of ZemberekNLP.
AI dan pembelajaran mesinPertumbuhan bintang terukur
- dalam 24 jam
- 0
- dalam 7 hari
- Mengumpulkan riwayat
- dalam 15 hari
- Mengumpulkan riwayat
- dalam 1 bulan
- Mengumpulkan riwayat
Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.
README.md
AsliZeyrek: Morphological Analyzer and Lemmatizer
Zeyrek is a partial port of the Zemberek library to Python for lemmatizing and analyzing Turkish language words. It is in alpha stage, and the API will probably change.
- Free software: MIT license
- Documentation: https://obulat.github.io/zeyrek/
Basic Usage
Install Zeyrek:
pip install zeyrek
or, in a project managed with uv:
uv add zeyrek
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.
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
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ş']]
A formatter writes the formatted string of a Parse. The default one follows Zemberek, and
formatter="UD" writes Universal Dependencies features:
>>> zeyrek.MorphAnalyzer(formatter="UD").analyze_word("kitaplarımdan")[0].formatted
'Case=Abl|Number=Plur|Number[psor]=Sing|Person=3|Person[psor]=1'
Zemberek's other formats, such as the Oflazer style (formatter="oflazer"), Oflazer's tags as
the treebanks write them (formatter="oflazer_strict"), the stem and ending
(formatter="stem_ending"), CoNLL-U (formatter="conllu"), Apertium (formatter="apertium") and
UniMorph (formatter="unimorph"), are there too. The documentation
explains each format and how to write your own formatter.
To read analyses as Leipzig glosses, or in Turkish or Russian grammar terms, create the analyzer with
formatter="leipzig", "turkish" or "russian". The documentation has examples.
Zeyrek splits texts into sentences and words with a port of Zemberek's tokenizer, which you can also use on its own:
>>> from zeyrek.tokenization import sentences, tokenize
>>> sentences("Prof. Dr. Ali geldi. Saat 10.30'da gitti!")
['Prof. Dr. Ali geldi.', "Saat 10.30'da gitti!"]
>>> [token.text for token in tokenize("H.T.'nin 2. kitabı 10:30'da çıktı.")]
["H.T.'nin", '2.', 'kitabı', "10:30'da", 'çıktı', '.']
detokenize joins tokens back into text, spaced as Turkish is written:
>>> from zeyrek.tokenization import detokenize
>>> detokenize(["(", "2020", ")", "'", "de", "“", "Ali", "”", "dedi", ":", "$", "40", "."])
"(2020)'de “Ali” dedi: $40."
zeyrek.numbers writes numbers in Turkish words and reads them back:
>>> from zeyrek import numbers
>>> numbers.to_words(1990), numbers.ordinal_to_words("101.")
('bin dokuz yüz doksan', 'yüz birinci')
>>> numbers.to_number("iki bin üç yüz kırk beş")
2345
SpellChecker checks the spelling of words and suggests corrections:
>>> checker = zeyrek.SpellChecker()
>>> checker.check("öğretmenlerimizdn")
False
>>> checker.suggest("öğretmenlerimizdn")
['öğretmenlerimizin', 'öğretmenlerimizden', 'öğretmenlerimizde', 'öğretmenlerimizdi']
suggest_in_context ranks the suggestions by the words before and after the misspelling,
with None for the start or end of a sentence:
>>> checker.suggest("adm")[:3]
['adam', 'adı', 'adım']
>>> checker.suggest_in_context("adm", "benim", None)[:3]
['adım', 'adam', 'adı']
zeyrek.hyphenation splits words into syllables and finds where to hyphenate them:
>>> from zeyrek.hyphenation import split_index, syllables
>>> syllables("merhaba")
['mer', 'ha', 'ba']
>>> split_index("merhaba", 6)
5
LanguageIdentifier finds the language of a text, with the models that
pip install "zeyrek[langid]" installs:
>>> from zeyrek.langid import LanguageIdentifier
>>> identifier = LanguageIdentifier()
>>> identifier.identify("Merhaba dünya ve tüm gezegenler.")
'tr'
>>> identifier.identify("Hello world and all the planets.")
'en'
DependencyParser finds the head of each word of a sentence and its relation to it, with
Zemberek's dependency parser model, which pip install "zeyrek[dependency]" installs. The
documentation shows its CoNLL-U output:
>>> parser = zeyrek.DependencyParser()
>>> for node in parser.parse("Kitapları masaya koydum."):
... print(node.id, node.form, node.head, node.deprel)
1 Kitapları 3 obj
2 masaya 3 obl
3 koydum 0 root
4 . 3 punct
generate_from_item builds words from a dictionary item and a list of morphemes, as
Zemberek's word generator does:
>>> [
... parse.word
... for parse in analyzer.generate_from_item("kitap_Noun", ["A3pl", "P1sg", "Abl"])
... ]
['kitaplarımdan']
With informal=True, the analyzer also reads spoken Turkish, and to_formal converts each
analysis of an informal word to the formal word:
>>> informal_analyzer = zeyrek.MorphAnalyzer(informal=True)
>>> [parse.word for parse in informal_analyzer.to_formal("yapmıycam")]
['yapmayacağım']
LatticeDeasciifier restores the Turkish letters of text typed without them, choosing each
word's spelling by the words around it:
>>> zeyrek.LatticeDeasciifier().deasciify("Isik sondu, hala gelmedi.")
'Işık söndü, hâlâ gelmedi.'
SentenceNormalizer rewrites a noisy sentence in standard Turkish: it restores Turkish
letters, corrects typos, turns informal and shorthand words into formal ones, splits and
joins words, and fixes casing and apostrophes:
>>> zeyrek.SentenceNormalizer().normalize(
... "Tmm, yarin havuza giricem ve aksama kadar yaticam :)"
... )
'Tamam, yarın havuza gireceğim ve akşama kadar yatacağım :)'
Credits
This package is a Python port of part of the Zemberek package by Ahmet A. Akın and Mehmet D. Akın. Its dictionaries, disambiguation model, deasciifier models, normalization models, language identification models and dependency parser model come from Zemberek, which is under the Apache License 2.0. See LICENSE-zemberek, and for the models of the extras, the license of the language identification models and of the dependency parser model.
Jelajahi proyek terkait
Memuat…