turkce-kit 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.
- turkce_kit/__init__.py +45 -0
- turkce_kit/_case.py +32 -0
- turkce_kit/_numbers.py +150 -0
- turkce_kit/_sort.py +49 -0
- turkce_kit/_text.py +41 -0
- turkce_kit/_validators.py +144 -0
- turkce_kit/py.typed +0 -0
- turkce_kit-0.1.0.dist-info/METADATA +123 -0
- turkce_kit-0.1.0.dist-info/RECORD +11 -0
- turkce_kit-0.1.0.dist-info/WHEEL +4 -0
- turkce_kit-0.1.0.dist-info/licenses/LICENSE +21 -0
turkce_kit/__init__.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""turkce-kit: Türkçe metin araçları ve Türkiye'ye özgü doğrulayıcılar.
|
|
2
|
+
|
|
3
|
+
Python ve TypeScript sürümleri aynı API'yi sunar ve aynı test
|
|
4
|
+
vektörlerinden geçer.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from ._case import equals_ignore_case, lower, title, upper
|
|
8
|
+
from ._numbers import CURRENCIES, amount_to_words, number_to_words
|
|
9
|
+
from ._sort import compare, sort, sort_key
|
|
10
|
+
from ._text import slugify, to_ascii
|
|
11
|
+
from ._validators import (
|
|
12
|
+
format_iban,
|
|
13
|
+
is_valid_iban,
|
|
14
|
+
is_valid_phone,
|
|
15
|
+
is_valid_plate,
|
|
16
|
+
is_valid_tckn,
|
|
17
|
+
is_valid_vkn,
|
|
18
|
+
normalize_phone,
|
|
19
|
+
normalize_plate,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
__version__ = "0.1.0"
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"lower",
|
|
26
|
+
"upper",
|
|
27
|
+
"title",
|
|
28
|
+
"equals_ignore_case",
|
|
29
|
+
"sort_key",
|
|
30
|
+
"compare",
|
|
31
|
+
"sort",
|
|
32
|
+
"to_ascii",
|
|
33
|
+
"slugify",
|
|
34
|
+
"number_to_words",
|
|
35
|
+
"amount_to_words",
|
|
36
|
+
"CURRENCIES",
|
|
37
|
+
"is_valid_tckn",
|
|
38
|
+
"is_valid_vkn",
|
|
39
|
+
"is_valid_iban",
|
|
40
|
+
"format_iban",
|
|
41
|
+
"normalize_plate",
|
|
42
|
+
"is_valid_plate",
|
|
43
|
+
"normalize_phone",
|
|
44
|
+
"is_valid_phone",
|
|
45
|
+
]
|
turkce_kit/_case.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Türkçe kurallarına uygun büyük/küçük harf dönüşümleri."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
__all__ = ["lower", "upper", "title", "equals_ignore_case"]
|
|
6
|
+
|
|
7
|
+
_WORD_START = re.compile(r"(^|[\s\-])(\S)")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def lower(text: str) -> str:
|
|
11
|
+
"""Metni Türkçe kurallarıyla küçük harfe çevirir. ``"IŞIK" -> "ışık"``"""
|
|
12
|
+
text = text.replace("İ", "i").replace("İ", "i").replace("I", "ı")
|
|
13
|
+
return text.lower()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def upper(text: str) -> str:
|
|
17
|
+
"""Metni Türkçe kurallarıyla büyük harfe çevirir. ``"istanbul" -> "İSTANBUL"``"""
|
|
18
|
+
return text.replace("i", "İ").replace("ı", "I").upper()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def title(text: str) -> str:
|
|
22
|
+
"""Her kelimenin ilk harfini büyütür, gerisini küçültür.
|
|
23
|
+
|
|
24
|
+
Kesme işaretinden sonra büyütmez: ``"istanbul'da" -> "İstanbul'da"``.
|
|
25
|
+
Kısa çizgiden sonra büyütür: ``"ali-ihsan" -> "Ali-İhsan"``.
|
|
26
|
+
"""
|
|
27
|
+
return _WORD_START.sub(lambda m: m.group(1) + upper(m.group(2)), lower(text))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def equals_ignore_case(a: str, b: str) -> bool:
|
|
31
|
+
"""İki metni Türkçe kurallarıyla büyük/küçük harf ayırt etmeden karşılaştırır."""
|
|
32
|
+
return lower(a) == lower(b)
|
turkce_kit/_numbers.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Sayıları ve para tutarlarını Türkçe yazıya çevirme."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
|
5
|
+
from typing import Union
|
|
6
|
+
|
|
7
|
+
__all__ = ["number_to_words", "amount_to_words", "CURRENCIES"]
|
|
8
|
+
|
|
9
|
+
_ONES = ["", "bir", "iki", "üç", "dört", "beş", "altı", "yedi", "sekiz", "dokuz"]
|
|
10
|
+
_TENS = ["", "on", "yirmi", "otuz", "kırk", "elli", "altmış", "yetmiş", "seksen", "doksan"]
|
|
11
|
+
_SCALES = ["", "bin", "milyon", "milyar", "trilyon", "katrilyon", "kentilyon"]
|
|
12
|
+
_LIMIT = 10 ** (3 * len(_SCALES)) # 10^21
|
|
13
|
+
|
|
14
|
+
CURRENCIES = {
|
|
15
|
+
"TRY": ("lira", "kuruş"),
|
|
16
|
+
"USD": ("dolar", "sent"),
|
|
17
|
+
"EUR": ("avro", "sent"),
|
|
18
|
+
"GBP": ("sterlin", "peni"),
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _under_thousand(n: int) -> list:
|
|
23
|
+
words = []
|
|
24
|
+
hundreds, rest = divmod(n, 100)
|
|
25
|
+
if hundreds:
|
|
26
|
+
if hundreds > 1:
|
|
27
|
+
words.append(_ONES[hundreds])
|
|
28
|
+
words.append("yüz")
|
|
29
|
+
tens, ones = divmod(rest, 10)
|
|
30
|
+
if tens:
|
|
31
|
+
words.append(_TENS[tens])
|
|
32
|
+
if ones:
|
|
33
|
+
words.append(_ONES[ones])
|
|
34
|
+
return words
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def number_to_words(number: int) -> str:
|
|
38
|
+
"""Tam sayıyı Türkçe yazıya çevirir. ``1234 -> "bin iki yüz otuz dört"``
|
|
39
|
+
|
|
40
|
+
Mutlak değeri 10^21'den küçük tam sayıları destekler (kentilyona kadar).
|
|
41
|
+
"""
|
|
42
|
+
if isinstance(number, bool) or not isinstance(number, int):
|
|
43
|
+
raise TypeError("number_to_words yalnızca tam sayı (int) kabul eder")
|
|
44
|
+
if abs(number) >= _LIMIT:
|
|
45
|
+
raise ValueError("Sayı desteklenen aralığın dışında (|n| < 10^21)")
|
|
46
|
+
if number == 0:
|
|
47
|
+
return "sıfır"
|
|
48
|
+
if number < 0:
|
|
49
|
+
return "eksi " + number_to_words(-number)
|
|
50
|
+
|
|
51
|
+
groups = []
|
|
52
|
+
while number:
|
|
53
|
+
number, group = divmod(number, 1000)
|
|
54
|
+
groups.append(group)
|
|
55
|
+
|
|
56
|
+
words = []
|
|
57
|
+
for index in range(len(groups) - 1, -1, -1):
|
|
58
|
+
group = groups[index]
|
|
59
|
+
if not group:
|
|
60
|
+
continue
|
|
61
|
+
if index == 1 and group == 1:
|
|
62
|
+
words.append("bin") # "bir bin" değil, "bin"
|
|
63
|
+
continue
|
|
64
|
+
words.extend(_under_thousand(group))
|
|
65
|
+
if index:
|
|
66
|
+
words.append(_SCALES[index])
|
|
67
|
+
return " ".join(words)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# Desteklenen en büyük tutar 21 basamaklı; çok uzun girdiler baştan reddedilir.
|
|
71
|
+
_MAX_AMOUNT_CHARS = 64
|
|
72
|
+
|
|
73
|
+
_GROUPED = re.compile(r"^[0-9]{1,3}(\.[0-9]{3})+$|^[0-9]{1,3}(,[0-9]{3})+$")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _parse_amount(text: str) -> Decimal:
|
|
77
|
+
if len(text) > _MAX_AMOUNT_CHARS:
|
|
78
|
+
raise ValueError("Tutar metni çok uzun")
|
|
79
|
+
s = text.strip().replace(" ", "")
|
|
80
|
+
sign = ""
|
|
81
|
+
if s[:1] in "+-" and s:
|
|
82
|
+
sign, s = s[0], s[1:]
|
|
83
|
+
if not s or not re.fullmatch(r"[0-9.,]+", s):
|
|
84
|
+
raise ValueError(f"Geçersiz tutar: {text!r}")
|
|
85
|
+
|
|
86
|
+
last_dot, last_comma = s.rfind("."), s.rfind(",")
|
|
87
|
+
if last_dot >= 0 and last_comma >= 0:
|
|
88
|
+
dec_sep = "." if last_dot > last_comma else ","
|
|
89
|
+
elif last_comma >= 0:
|
|
90
|
+
dec_sep = "," if s.count(",") == 1 else None
|
|
91
|
+
elif last_dot >= 0:
|
|
92
|
+
dec_sep = "." if s.count(".") == 1 else None
|
|
93
|
+
else:
|
|
94
|
+
dec_sep = None
|
|
95
|
+
|
|
96
|
+
if dec_sep:
|
|
97
|
+
int_part, frac_part = s.rsplit(dec_sep, 1)
|
|
98
|
+
if not re.fullmatch(r"[0-9]+", frac_part):
|
|
99
|
+
raise ValueError(f"Geçersiz tutar: {text!r}")
|
|
100
|
+
else:
|
|
101
|
+
int_part, frac_part = s, ""
|
|
102
|
+
|
|
103
|
+
if not re.fullmatch(r"[0-9]+", int_part):
|
|
104
|
+
if not _GROUPED.match(int_part) or (dec_sep and dec_sep in int_part):
|
|
105
|
+
raise ValueError(f"Geçersiz tutar: {text!r}")
|
|
106
|
+
int_part = int_part.replace(".", "").replace(",", "")
|
|
107
|
+
|
|
108
|
+
return Decimal(f"{sign}{int_part}.{frac_part or '0'}")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def amount_to_words(amount: Union[str, int, float, Decimal], currency: str = "TRY") -> str:
|
|
112
|
+
"""Para tutarını Türkçe yazıya çevirir (faturalardaki "yalnız ..." satırı için).
|
|
113
|
+
|
|
114
|
+
``"123,45" -> "yüz yirmi üç lira kırk beş kuruş"``
|
|
115
|
+
|
|
116
|
+
- Metin girdide hem ``1.234,56`` (Türkçe) hem ``1,234.56`` biçimi anlaşılır.
|
|
117
|
+
Tek ayraç varsa ondalık ayracı sayılır.
|
|
118
|
+
- Kuruşlar 2 basamağa yarım yukarı yuvarlanır.
|
|
119
|
+
- Kesin sonuç için ``float`` yerine metin ya da ``Decimal`` verin.
|
|
120
|
+
"""
|
|
121
|
+
units = CURRENCIES.get(currency.upper())
|
|
122
|
+
if units is None:
|
|
123
|
+
raise ValueError(f"Bilinmeyen para birimi: {currency!r}. Desteklenen: {', '.join(CURRENCIES)}")
|
|
124
|
+
main_unit, sub_unit = units
|
|
125
|
+
|
|
126
|
+
if isinstance(amount, bool):
|
|
127
|
+
raise TypeError("Geçersiz tutar türü")
|
|
128
|
+
if isinstance(amount, str):
|
|
129
|
+
value = _parse_amount(amount)
|
|
130
|
+
elif isinstance(amount, (int, float)):
|
|
131
|
+
value = Decimal(repr(amount)) if isinstance(amount, float) else Decimal(amount)
|
|
132
|
+
elif isinstance(amount, Decimal):
|
|
133
|
+
value = amount
|
|
134
|
+
else:
|
|
135
|
+
raise TypeError("Geçersiz tutar türü")
|
|
136
|
+
try:
|
|
137
|
+
cents = int((abs(value) * 100).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
|
|
138
|
+
except InvalidOperation:
|
|
139
|
+
raise ValueError(f"Geçersiz tutar: {amount!r}") from None
|
|
140
|
+
|
|
141
|
+
whole, frac = divmod(cents, 100)
|
|
142
|
+
parts = []
|
|
143
|
+
if whole:
|
|
144
|
+
parts.append(f"{number_to_words(whole)} {main_unit}")
|
|
145
|
+
if frac:
|
|
146
|
+
parts.append(f"{number_to_words(frac)} {sub_unit}")
|
|
147
|
+
if not parts:
|
|
148
|
+
return f"sıfır {main_unit}"
|
|
149
|
+
prefix = "eksi " if value < 0 else ""
|
|
150
|
+
return prefix + " ".join(parts)
|
turkce_kit/_sort.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Türk alfabesine göre sıralama."""
|
|
2
|
+
|
|
3
|
+
from typing import Iterable, List, Tuple
|
|
4
|
+
|
|
5
|
+
from ._case import lower
|
|
6
|
+
|
|
7
|
+
__all__ = ["sort_key", "compare", "sort"]
|
|
8
|
+
|
|
9
|
+
# Q, W, X Türk alfabesinde yok ama yabancı kelimeler için CLDR'deki yerlerine konur.
|
|
10
|
+
_ALPHABET = "abcçdefgğhıijklmnoöpqrsştuüvwxyz"
|
|
11
|
+
_LETTER_RANK = {ch: 100 + i for i, ch in enumerate(_ALPHABET)}
|
|
12
|
+
_ACCENT_FOLD = {"â": "a", "î": "i", "û": "u"}
|
|
13
|
+
|
|
14
|
+
Key = Tuple[Tuple[int, ...], Tuple[int, ...], Tuple[int, ...]]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _primary(ch: str) -> int:
|
|
18
|
+
ch = _ACCENT_FOLD.get(ch, ch)
|
|
19
|
+
if "0" <= ch <= "9":
|
|
20
|
+
return ord(ch) - ord("0")
|
|
21
|
+
rank = _LETTER_RANK.get(ch)
|
|
22
|
+
if rank is not None:
|
|
23
|
+
return rank
|
|
24
|
+
return 1000 + ord(ch)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def sort_key(text: str) -> Key:
|
|
28
|
+
"""``sorted(liste, key=sort_key)`` ile kullanılabilecek sıralama anahtarı.
|
|
29
|
+
|
|
30
|
+
Sıra: önce harfler (Türk alfabesi, â/î/û aksansız sayılır), sonra
|
|
31
|
+
küçük harf büyük harften önce gelir, en son karakter kodlarına bakılır.
|
|
32
|
+
"""
|
|
33
|
+
# Karakter karakter küçültülür; böylece uzunluk değişmez ve TS sürümüyle birebir aynı olur.
|
|
34
|
+
low = [lower(c)[:1] or c for c in text]
|
|
35
|
+
primary = tuple(_primary(c) for c in low)
|
|
36
|
+
case = tuple(0 if c == lc else 1 for c, lc in zip(text, low))
|
|
37
|
+
raw = tuple(ord(c) for c in text)
|
|
38
|
+
return (primary, case, raw)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def compare(a: str, b: str) -> int:
|
|
42
|
+
"""``a`` önce gelirse -1, eşitse 0, sonra gelirse 1 döner."""
|
|
43
|
+
ka, kb = sort_key(a), sort_key(b)
|
|
44
|
+
return (ka > kb) - (ka < kb)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def sort(items: Iterable[str], reverse: bool = False) -> List[str]:
|
|
48
|
+
"""Metinleri Türk alfabesine göre sıralanmış yeni bir liste olarak döndürür."""
|
|
49
|
+
return sorted(items, key=sort_key, reverse=reverse)
|
turkce_kit/_text.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Slug üretme ve ASCII'ye çevirme."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import unicodedata
|
|
5
|
+
|
|
6
|
+
from ._case import lower
|
|
7
|
+
|
|
8
|
+
__all__ = ["to_ascii", "slugify"]
|
|
9
|
+
|
|
10
|
+
_TR_ASCII = str.maketrans(
|
|
11
|
+
{
|
|
12
|
+
"ç": "c", "Ç": "C",
|
|
13
|
+
"ğ": "g", "Ğ": "G",
|
|
14
|
+
"ı": "i", "İ": "I",
|
|
15
|
+
"ö": "o", "Ö": "O",
|
|
16
|
+
"ş": "s", "Ş": "S",
|
|
17
|
+
"ü": "u", "Ü": "U",
|
|
18
|
+
"â": "a", "Â": "A",
|
|
19
|
+
"î": "i", "Î": "I",
|
|
20
|
+
"û": "u", "Û": "U",
|
|
21
|
+
}
|
|
22
|
+
)
|
|
23
|
+
_APOSTROPHES = re.compile(r"['’ʼ]")
|
|
24
|
+
_NON_ALNUM = re.compile(r"[^a-z0-9]+")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def to_ascii(text: str) -> str:
|
|
28
|
+
"""Yalnızca Türkçe harfleri ASCII karşılıklarına çevirir, büyük/küçük harfi korur.
|
|
29
|
+
|
|
30
|
+
``"Çağrı Işık" -> "Cagri Isik"``. Diğer karakterlere dokunmaz.
|
|
31
|
+
"""
|
|
32
|
+
return text.translate(_TR_ASCII)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def slugify(text: str, separator: str = "-") -> str:
|
|
36
|
+
"""URL dostu kısa ad üretir. ``"İstanbul'da Çok Güzel!" -> "istanbulda-cok-guzel"``"""
|
|
37
|
+
text = to_ascii(lower(_APOSTROPHES.sub("", text)))
|
|
38
|
+
text = unicodedata.normalize("NFKD", text)
|
|
39
|
+
text = "".join(c for c in text if not unicodedata.category(c).startswith("M"))
|
|
40
|
+
text = _NON_ALNUM.sub(" ", text.lower()).strip()
|
|
41
|
+
return separator.join(text.split())
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Türkiye'ye özgü doğrulayıcılar: TCKN, VKN, IBAN, plaka, telefon."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from typing import Optional, Union
|
|
5
|
+
|
|
6
|
+
from ._case import upper
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"is_valid_tckn",
|
|
10
|
+
"is_valid_vkn",
|
|
11
|
+
"is_valid_iban",
|
|
12
|
+
"format_iban",
|
|
13
|
+
"normalize_plate",
|
|
14
|
+
"is_valid_plate",
|
|
15
|
+
"normalize_phone",
|
|
16
|
+
"is_valid_phone",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _as_text(value: Union[str, int]) -> str:
|
|
21
|
+
if isinstance(value, bool):
|
|
22
|
+
return ""
|
|
23
|
+
return str(value).strip() if isinstance(value, (str, int)) else ""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def is_valid_tckn(value: Union[str, int]) -> bool:
|
|
27
|
+
"""T.C. Kimlik Numarasının algoritmaya uygun olup olmadığını kontrol eder.
|
|
28
|
+
|
|
29
|
+
Yalnızca matematiksel kontrol yapar; numaranın gerçekten birine ait
|
|
30
|
+
olduğunu doğrulamaz.
|
|
31
|
+
"""
|
|
32
|
+
s = _as_text(value)
|
|
33
|
+
if not re.fullmatch(r"[1-9][0-9]{10}", s):
|
|
34
|
+
return False
|
|
35
|
+
d = [int(c) for c in s]
|
|
36
|
+
odd, even = sum(d[0:9:2]), sum(d[1:8:2])
|
|
37
|
+
if (odd * 7 - even) % 10 != d[9]:
|
|
38
|
+
return False
|
|
39
|
+
return sum(d[:10]) % 10 == d[10]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def is_valid_vkn(value: Union[str, int]) -> bool:
|
|
43
|
+
"""10 haneli Vergi Kimlik Numarasının algoritmaya uygun olup olmadığını kontrol eder."""
|
|
44
|
+
s = _as_text(value)
|
|
45
|
+
if not re.fullmatch(r"[0-9]{10}", s):
|
|
46
|
+
return False
|
|
47
|
+
total = 0
|
|
48
|
+
for i in range(9):
|
|
49
|
+
t = (int(s[i]) + 9 - i) % 10
|
|
50
|
+
total += 9 if t == 9 else (t * 2 ** (9 - i)) % 9
|
|
51
|
+
return (10 - total % 10) % 10 == int(s[9])
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _clean_iban(value: str) -> str:
|
|
55
|
+
return re.sub(r"\s+", "", value).upper() if isinstance(value, str) else ""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def is_valid_iban(value: str) -> bool:
|
|
59
|
+
"""IBAN'ı mod-97 ile doğrular. Boşluklar ve küçük harf kabul edilir.
|
|
60
|
+
|
|
61
|
+
TR IBAN'ları için ayrıca uzunluk (26) ve biçim kontrolü yapılır.
|
|
62
|
+
"""
|
|
63
|
+
s = _clean_iban(value)
|
|
64
|
+
if not re.fullmatch(r"[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}", s):
|
|
65
|
+
return False
|
|
66
|
+
if s.startswith("TR") and not re.fullmatch(r"TR[0-9]{24}", s):
|
|
67
|
+
return False
|
|
68
|
+
rearranged = s[4:] + s[:4]
|
|
69
|
+
remainder = 0
|
|
70
|
+
for ch in rearranged:
|
|
71
|
+
part = str(int(ch, 36))
|
|
72
|
+
for digit in part:
|
|
73
|
+
remainder = (remainder * 10 + int(digit)) % 97
|
|
74
|
+
return remainder == 1
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def format_iban(value: str) -> Optional[str]:
|
|
78
|
+
"""Geçerli IBAN'ı 4'erli gruplar halinde yazar, geçersizse ``None`` döner."""
|
|
79
|
+
if not is_valid_iban(value):
|
|
80
|
+
return None
|
|
81
|
+
s = _clean_iban(value)
|
|
82
|
+
return " ".join(s[i : i + 4] for i in range(0, len(s), 4))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
_PLATE = re.compile(r"([0-9]{2})([A-Z]{1,3})([0-9]{2,5})")
|
|
86
|
+
_PLATE_LETTERS = set("ABCDEFGHIJKLMNOPRSTUVYZ")
|
|
87
|
+
_PLATE_DIGITS = {1: (4, 5), 2: (3, 4), 3: (2, 3)}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def normalize_plate(value: str) -> Optional[str]:
|
|
91
|
+
"""Türk araç plakasını ``"34 ABC 123"`` biçimine getirir, geçersizse ``None`` döner.
|
|
92
|
+
|
|
93
|
+
Kurallar: il kodu 01-81; 1 harf + 4-5 rakam, 2 harf + 3-4 rakam veya
|
|
94
|
+
3 harf + 2-3 rakam. Q, W, X ve Türkçe karakterler plakada kullanılmaz.
|
|
95
|
+
"""
|
|
96
|
+
if not isinstance(value, str):
|
|
97
|
+
return None
|
|
98
|
+
s = re.sub(r"[\s\-]+", "", upper(value)).replace("İ", "I")
|
|
99
|
+
m = _PLATE.fullmatch(s)
|
|
100
|
+
if not m:
|
|
101
|
+
return None
|
|
102
|
+
city, letters, digits = m.groups()
|
|
103
|
+
if not 1 <= int(city) <= 81:
|
|
104
|
+
return None
|
|
105
|
+
if not set(letters) <= _PLATE_LETTERS:
|
|
106
|
+
return None
|
|
107
|
+
lo, hi = _PLATE_DIGITS[len(letters)]
|
|
108
|
+
if not lo <= len(digits) <= hi:
|
|
109
|
+
return None
|
|
110
|
+
return f"{city} {letters} {digits}"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def is_valid_plate(value: str) -> bool:
|
|
114
|
+
"""Plakanın Türk plaka kurallarına uyup uymadığını döndürür."""
|
|
115
|
+
return normalize_plate(value) is not None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def normalize_phone(value: str) -> Optional[str]:
|
|
119
|
+
"""Türkiye telefon numarasını E.164 biçimine (``+905321234567``) getirir.
|
|
120
|
+
|
|
121
|
+
Geçersizse ``None`` döner. Ulusal numaranın 2, 3, 4, 5 veya 8 ile
|
|
122
|
+
başlaması beklenir (sabit hat, GSM, 850 vb.).
|
|
123
|
+
"""
|
|
124
|
+
if not isinstance(value, str):
|
|
125
|
+
return None
|
|
126
|
+
digits = re.sub(r"[^0-9]", "", value)
|
|
127
|
+
if digits.startswith("0090"):
|
|
128
|
+
digits = digits[2:]
|
|
129
|
+
if len(digits) == 12 and digits.startswith("90"):
|
|
130
|
+
national = digits[2:]
|
|
131
|
+
elif len(digits) == 11 and digits.startswith("0"):
|
|
132
|
+
national = digits[1:]
|
|
133
|
+
elif len(digits) == 10:
|
|
134
|
+
national = digits
|
|
135
|
+
else:
|
|
136
|
+
return None
|
|
137
|
+
if national[0] not in "23458":
|
|
138
|
+
return None
|
|
139
|
+
return "+90" + national
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def is_valid_phone(value: str) -> bool:
|
|
143
|
+
"""Telefon numarasının geçerli bir Türkiye numarası olup olmadığını döndürür."""
|
|
144
|
+
return normalize_phone(value) is not None
|
turkce_kit/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: turkce-kit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Türkçe metin araçları (doğru İ/ı dönüşümü, alfabetik sıralama, slug, sayı ve tutarı yazıya çevirme) ve TCKN, VKN, IBAN, plaka, telefon doğrulayıcıları.
|
|
5
|
+
Project-URL: Homepage, https://github.com/CoshkaX/turkce-kit
|
|
6
|
+
Project-URL: Issues, https://github.com/CoshkaX/turkce-kit/issues
|
|
7
|
+
Author: CoshkaX
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: e-fatura,iban,plaka,sayıyı yazıya,slug,tckn,turkish,türkçe,vkn
|
|
11
|
+
Classifier: Natural Language :: Turkish
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Provides-Extra: test
|
|
17
|
+
Requires-Dist: pytest>=7; extra == 'test'
|
|
18
|
+
Requires-Dist: python-stdnum>=1.19; extra == 'test'
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# turkce-kit
|
|
22
|
+
|
|
23
|
+
Türkçe metin araçları ve Türkiye'ye özgü doğrulayıcılar. **Python ve TypeScript için aynı API.**
|
|
24
|
+
|
|
25
|
+
```text
|
|
26
|
+
"IŞIK".lower() → "işik" ❌ lower("IŞIK") → "ışık" ✅
|
|
27
|
+
"istanbul".upper() → "ISTANBUL" ❌ upper("istanbul") → "İSTANBUL" ✅
|
|
28
|
+
sorted(["şeker","su","zeytin"]) → ["su","zeytin","şeker"] ❌
|
|
29
|
+
sort(["şeker","su","zeytin"]) → ["su","şeker","zeytin"] ✅
|
|
30
|
+
amount_to_words("1.234,56") → "bin iki yüz otuz dört lira elli altı kuruş"
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
- **Sıfır bağımlılık**, her iki dilde de.
|
|
34
|
+
- **İki dil, tek gerçek:** Python ve TypeScript sürümleri [`spec/vectors.json`](spec/vectors.json) içindeki ortak test örneklerinin hepsinden geçmek zorundadır. Aynı girdi her iki dilde de aynı çıktıyı verir.
|
|
35
|
+
- TCKN ve VKN algoritmaları bağımsız bir kütüphaneyle ([python-stdnum](https://github.com/arthurdejong/python-stdnum)) on binlerce rastgele numarada çapraz kontrol edilir.
|
|
36
|
+
|
|
37
|
+
## Kurulum
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install turkce-kit # Python 3.9+
|
|
41
|
+
npm install turkce-kit # Node 18+, tarayıcı; ESM + CommonJS + TypeScript tipleri
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Kullanım
|
|
45
|
+
|
|
46
|
+
### Python
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
import turkce_kit as tk
|
|
50
|
+
|
|
51
|
+
tk.lower("DİYARBAKIR") # "diyarbakır"
|
|
52
|
+
tk.title("istanbul'da güzel bir gün") # "İstanbul'da Güzel Bir Gün"
|
|
53
|
+
tk.sort(["çay", "cam", "ılık", "inek"]) # ["cam", "çay", "ılık", "inek"]
|
|
54
|
+
sorted(kelimeler, key=tk.sort_key) # sorted() ile de çalışır
|
|
55
|
+
|
|
56
|
+
tk.slugify("Kâğıt & Işık Fiyatları") # "kagit-isik-fiyatlari"
|
|
57
|
+
tk.number_to_words(2_500_000) # "iki milyon beş yüz bin"
|
|
58
|
+
tk.amount_to_words("15.99", "USD") # "on beş dolar doksan dokuz sent"
|
|
59
|
+
|
|
60
|
+
tk.is_valid_tckn("10000000146") # True
|
|
61
|
+
tk.format_iban("tr330006100519786457841326") # "TR33 0006 1005 1978 6457 8413 26"
|
|
62
|
+
tk.normalize_plate("34abc123") # "34 ABC 123"
|
|
63
|
+
tk.normalize_phone("0532 123 45 67") # "+905321234567"
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### TypeScript / JavaScript
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import * as tk from "turkce-kit";
|
|
70
|
+
|
|
71
|
+
tk.lower("DİYARBAKIR"); // "diyarbakır"
|
|
72
|
+
["şeker", "su", "çay"].sort(tk.compare); // ["çay", "su", "şeker"]
|
|
73
|
+
tk.numberToWords(9007199254740993n); // bigint de kabul eder
|
|
74
|
+
tk.amountToWords("123,45"); // "yüz yirmi üç lira kırk beş kuruş"
|
|
75
|
+
tk.isValidIban("TR33 0006 1005 1978 6457 8413 26"); // true
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Fonksiyonlar
|
|
79
|
+
|
|
80
|
+
| Python | TypeScript | Ne yapar |
|
|
81
|
+
|---|---|---|
|
|
82
|
+
| `lower`, `upper` | `lower`, `upper` | Türkçe kurallarıyla büyük/küçük harf (I↔ı, İ↔i) |
|
|
83
|
+
| `title` | `title` | Kelime başlarını büyütür; kesme işaretinden sonra büyütmez |
|
|
84
|
+
| `equals_ignore_case` | `equalsIgnoreCase` | Büyük/küçük harf duyarsız karşılaştırma |
|
|
85
|
+
| `sort`, `compare`, `sort_key` | `sort`, `compare`, `sortKey` | Türk alfabesine göre sıralama (ç, ğ, ı, ö, ş, ü doğru yerde; â/î/û aksansız sayılır) |
|
|
86
|
+
| `slugify` | `slugify` | URL dostu kısa ad |
|
|
87
|
+
| `to_ascii` | `toAscii` | Yalnızca Türkçe harfleri ASCII'ye çevirir, büyük/küçük harfi korur |
|
|
88
|
+
| `number_to_words` | `numberToWords` | Tam sayıyı yazıya çevirir (10²¹'e kadar, negatifler dahil) |
|
|
89
|
+
| `amount_to_words` | `amountToWords` | Para tutarını yazıya çevirir: TRY, USD, EUR, GBP |
|
|
90
|
+
| `is_valid_tckn` | `isValidTckn` | T.C. Kimlik No algoritma kontrolü |
|
|
91
|
+
| `is_valid_vkn` | `isValidVkn` | Vergi Kimlik No algoritma kontrolü |
|
|
92
|
+
| `is_valid_iban`, `format_iban` | `isValidIban`, `formatIban` | IBAN doğrulama (mod-97) ve 4'erli gruplama |
|
|
93
|
+
| `normalize_plate`, `is_valid_plate` | `normalizePlate`, `isValidPlate` | Araç plakası (il kodu 01–81, harf/rakam sayısı kuralları) |
|
|
94
|
+
| `normalize_phone`, `is_valid_phone` | `normalizePhone`, `isValidPhone` | Türkiye telefon numarasını `+90…` biçimine getirir |
|
|
95
|
+
|
|
96
|
+
Geçersiz girdide `normalize_*` / `format_iban` Python'da `None`, TypeScript'te `null` döner.
|
|
97
|
+
|
|
98
|
+
### Tutarı yazıya çevirme kuralları
|
|
99
|
+
|
|
100
|
+
- Metin girdide hem `1.234,56` hem `1,234.56` anlaşılır. **Tek ayraç varsa ondalık ayracı sayılır**: `"1.234"` → "bir lira yirmi üç kuruş" (bin lira değil!). Binlik ayracı kullanacaksanız kuruşu da yazın: `"1.234,00"`.
|
|
101
|
+
- Kuruş 2 basamağa **yarım yukarı** yuvarlanır: `"1.005"` → "bir lira bir kuruş".
|
|
102
|
+
- Kesin sonuç için kayan noktalı sayı yerine **metin** (veya Python'da `Decimal`) verin.
|
|
103
|
+
|
|
104
|
+
### Sınırlar
|
|
105
|
+
|
|
106
|
+
- TCKN ve VKN kontrolleri yalnızca **matematikseldir**; numaranın gerçek bir kişiye veya şirkete ait olduğunu göstermez.
|
|
107
|
+
- IBAN'da TR dışındaki ülkeler için yalnızca genel biçim ve mod-97 kontrolü yapılır, ülkeye özgü uzunluk kontrolü yapılmaz.
|
|
108
|
+
|
|
109
|
+
## Geliştirme
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
# Python
|
|
113
|
+
cd python && pip install -e ".[test]" && pytest
|
|
114
|
+
|
|
115
|
+
# TypeScript
|
|
116
|
+
cd js && npm install && npm test
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Yeni bir davranış eklerken önce [`spec/vectors.json`](spec/vectors.json) dosyasına örneğini ekleyin, sonra iki dilde de uygulayın.
|
|
120
|
+
|
|
121
|
+
## Lisans
|
|
122
|
+
|
|
123
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
turkce_kit/__init__.py,sha256=s5I7Np0LFkHykFS_XimrWzugrd_lOiWMXLcPAiW_N1M,980
|
|
2
|
+
turkce_kit/_case.py,sha256=OaA5u33z-o6DQQCIj1jZfsZ3HAbjgoFsNF_rd9VFqKQ,1116
|
|
3
|
+
turkce_kit/_numbers.py,sha256=xLIyh65SNPsKmXvg-_7diJyiVey3gNN944Pjkojl5OI,5178
|
|
4
|
+
turkce_kit/_sort.py,sha256=DCi1KOV-p1DNTwxS1oJS2Qh-qbx-NffiEaE9qPtgQCk,1716
|
|
5
|
+
turkce_kit/_text.py,sha256=eir3ZeaUj_p9ZFC_g4eKQXF35jwPMmPmAG3duP2Bgdg,1204
|
|
6
|
+
turkce_kit/_validators.py,sha256=dWm6RR5Tj9DMKraO9yd6ntg0SkEWJQuWhsp9WKM3g98,4501
|
|
7
|
+
turkce_kit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
turkce_kit-0.1.0.dist-info/METADATA,sha256=3Zoqq3jCsaoL3QAQiWRNyx5YRpepMEfSvaXhd8gXwZY,5740
|
|
9
|
+
turkce_kit-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
turkce_kit-0.1.0.dist-info/licenses/LICENSE,sha256=pHqlKcYLvg_BxMngVsGkyPRw-Qkl-B2Zsairh_G1Yz8,1064
|
|
11
|
+
turkce_kit-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 CoshkaX
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|