Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
ademozay committed Feb 26, 2020
0 parents commit 3fac241
Show file tree
Hide file tree
Showing 12 changed files with 311 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Adem Özay

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
44 changes: 44 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
lügat
=====

*lugat*, `TDK Güncel Türkçe Sözlük <https://sozluk.gov.tr>`_'ün komut satırı üzerinden kullanılmasını sağlar.

.. image:: https://raw.githubusercontent.com/ademozay/lugat/master/lugat.gif
:alt: lugat önizlemesi
:width: 100%
:align: center

Nasıl Yüklenir
--------------
.. code:: shell
pip3 install lugat
Nasıl Kullanılır
----------------

* Komutun satırında

.. code:: shell
lugat <kelime>
* Python uygulaması içinde

.. code:: python
from lugat import lookup, LookupException
try:
word = lookup(word)
variations = word.get_variations()
for v in variations:
print(v.name)
print(v.origin)
print(v.meanings)
print(v.compound_words)
print(v.proverbs)
except LookupException:
pass
Binary file added lugat.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions lugat/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
try:
from dict import lookup, LookupException
except:
from .dict import lookup, LookupException
4 changes: 4 additions & 0 deletions lugat/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from .cli import main

if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions lugat/__version__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__ = "0.1.1"
73 changes: 73 additions & 0 deletions lugat/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import sys

from termcolor import colored

try:
from dict import lookup, LookupException
except:
from .dict import lookup, LookupException

def main():
search = ' '.join(sys.argv[1:])
if not search:
print("Lütfen en az bir harf yazınız.")
sys.exit(0)

word = lookup(search)

if word is not None:
variations = word.get_variations()

def colorize_variations():
text = ''
for i, v in enumerate(variations, start=1):
text += colored(v.name, 'yellow', attrs=['bold', 'underline'])
if len(variations) > 2:
text += ' {}'.format(colored(f'[{i}]', attrs=['dark']))
if v.origin:
text += ' - ' + colored(v.origin, 'yellow', attrs=['dark'])

text += '\n\n'
for m in v.meanings:
text += '• ' + m.text + ' '

if m.props:
text += colored(
', '.join(m.props),
'yellow', attrs=['dark'],
)

text += '\n'
for s in m.samples:
text += f""" {colored('Örnek', 'magenta')} """
text += f""" {colored(s.text, 'green')}"""
if s.authors:
text += '\n'
text += f""" {colored('Yazarlar', 'magenta')} """
text += colored(', '.join(s.authors), 'blue')
text += '\n'
else:
text += '\n'

if v.compound_words:
text += colored('Birleşik Kelimeler', 'cyan') + '\n'
text += '\n'.join(['• ' + c for c in v.compound_words])
text += '\n\n'

if v.proverbs:
text += colored(
'Atasözleri, Deyimler veya Birleşik Fiiller', 'cyan'
)
text += '\n'
text += '\n'.join(['• ' + p for p in v.proverbs])
text += '\n'

return text

out = colorize_variations()

print(out.rstrip('\n'))


if __name__ == "__main__":
main()
38 changes: 38 additions & 0 deletions lugat/dict.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import requests

try:
from word import new as new_word
except:
from .word import new as new_word


class LookupException(Exception):
pass


URL = 'https://sozluk.gov.tr/gts?ara={}'
USER_AGENT = (
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/80.0.3987.87 Safari/537.36'
)
HEADERS = {
'Host': 'sozluk.gov.tr',
'User-Agent': USER_AGENT
}


def lookup(search):
if search is None:
return None

try:
response = requests.get(URL.format(search), headers=HEADERS)
result = response.json()

if 'error' in result:
return None

return new_word(result)
except Exception as e:
raise LookupException('lookup error') from e
91 changes: 91 additions & 0 deletions lugat/word.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
from collections import namedtuple

Variation = namedtuple(
'Variation', 'name origin meanings compound_words proverbs'
)
Meaning = namedtuple(
'Meaning', 'text props samples'
)
Sample = namedtuple(
'Sample', 'text authors'
)


class Word:
__variations = []

def __init__(self, words):
for variation in words:
self.__parse_variations(variation)

def __parse_variations(self, variation):
name = variation['madde']
origin = variation['lisan']
meanings = self.__parse_meanings(variation)
compound_words = self.__parse_compound_words(variation)
proverbs = self.__parse_proverbs(variation)

self.__variations.append(Variation(
name, origin, meanings, compound_words, proverbs,
))

def __parse_meanings(self, variation):
meanings = []
_meanings = variation.get('anlamlarListe', [])
for m in _meanings:
text = m['anlam']
props = self.__parse_props(m)
samples = self.__parse_samples(m),

if len(samples) > 0:
samples = samples[0]

meanings.append(Meaning(text, props, samples))

return meanings

def __parse_props(self, meaning):
return list(map(
lambda p: p['tam_adi'],
meaning.get('ozelliklerListe', [])
))

def __parse_samples(self, meaning):
samples = []
_samples = meaning.get('orneklerListe', [])

for s in _samples:
text = s.get('ornek')
authors = list(map(
lambda a: a.get('tam_adi'),
s.get('yazar', []),
))

samples.append(Sample(text, authors))

return samples

def __parse_compound_words(self, variation):
compound_words = variation.get('birlesikler', '')

if compound_words is None: return []

return list(map(
lambda cw: cw.strip(),
compound_words.split(','),
))

def __parse_proverbs(self, variation):
proverbs = variation.get('atasozu', [])

return list(map(
lambda p: p['madde'],
proverbs,
))

def get_variations(self):
return self.__variations


def new(word):
return Word(word)
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
termcolor==1.1.0
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[metadata]
description-file = README.rst
32 changes: 32 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import re
from setuptools import setup


version = re.search(
'^__version__\s*=\s*"(.*)"',
open('lugat/__version__.py').read(),
re.M
).group(1)


with open("README.rst", "rb") as f:
long_descr = f.read().decode("utf-8")


setup(
name="lugat",
packages=["lugat"],
entry_points={
"console_scripts": ['lugat = lugat.__main__:main']
},
version=version,
description="TDK Güncel Türkçe Sözlük için komut satırı uygulaması.",
long_description=long_descr,
long_description_content_type="text/x-rst",
keywords="tdk,cli",
author="Adem Özay",
author_email="[email protected]",
url="https://github.com/ademozay/lugat",
install_requires=['termcolor'],
python_requries='>=3.7'
)

0 comments on commit 3fac241

Please sign in to comment.