import os
import re
import time
import unicodedata
from collections import defaultdict
from pathlib import Path
book_path = Path("quran-simple2.txt")
if not book_path.exists():
print("Current working directory:", os.getcwd())
print("Files here:", [p.name for p in Path(".").iterdir()])
raise FileNotFoundError(
"Place 'quran-simple2.txt' in the folder above or set the full path, "
r"e.g. Path(r'C:\Users\kadir\Downloads\quran-simple2.txt')"
)
def prepare_quran_text(raw_text: str, strip_diacritics: bool = True) -> str:
"""
Removes Tanzil 'surah|ayah|' prefixes and verse numbers, and optionally
strips Arabic tashkeel (vowel marks) so identical root words match cleanly.
"""
cleaned_lines = []
for line in raw_text.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
# Remove '1|1|' style prefixes if present
parts = line.split("|")
verse_text = parts[-1] if len(parts) >= 3 else line
cleaned_lines.append(verse_text)
text = "\n".join(cleaned_lines)
if strip_diacritics:
# Remove Arabic tashkeel / harakat combining marks
text = "".join(
ch for ch in text
if unicodedata.category(ch) != "Mn"
)
return text
def brute_force_scan_and_count(text: str):
"""
Exhaustively scans character-by-character to extract word tokens
and count every single word occurrence.
"""
total_words = 0
frequencies = defaultdict(int)
current_chars = []
n = len(text)
i = 0
while i < n:
ch = text[i].lower()
# Include letters/digits (works for Arabic & Latin) and combining marks
if ch.isalnum() or unicodedata.category(ch) == "Mn":
current_chars.append(ch)
else:
if current_chars:
word = "".join(current_chars)
if not word.isdigit(): # Skip standalone verse numbers
frequencies[word] += 1
total_words += 1
current_chars.clear()
i += 1
if current_chars:
word = "".join(current_chars)
if not word.isdigit():
frequencies[word] += 1
total_words += 1
return total_words, dict(frequencies)
def find_similar_frequency_groups(
frequencies: dict[str, int],
tolerance: int = 1,
max_seconds: float = 30.0,
deep_search: bool = True,
):
start_time = time.perf_counter()
sorted_items = sorted(frequencies.items(), key=lambda kv: (-kv[1], kv[0]))
vocab_size = len(sorted_items)
neighbors = {word: set() for word, _ in sorted_items}
timed_out = False
comparisons_done = 0
for idx_a, (word_a, freq_a) in enumerate(sorted_items):
if time.perf_counter() - start_time > max_seconds:
timed_out = True
break
for idx_b in range(idx_a + 1, vocab_size):
if (comparisons_done & 4095) == 0:
if time.perf_counter() - start_time > max_seconds:
timed_out = True
break
word_b, freq_b = sorted_items[idx_b]
comparisons_done += 1
diff = abs(freq_a - freq_b)
if diff <= tolerance:
neighbors[word_a].add(word_b)
neighbors[word_b].add(word_a)
if deep_search and diff > tolerance:
denom = max(freq_a, freq_b)
similarity = 1.0 - (diff / denom) if denom > 0 else 1.0
if similarity >= 0.90:
neighbors[word_a].add(word_b)
neighbors[word_b].add(word_a)
if timed_out:
break
visited = set()
groups = []
for word, _ in sorted_items:
if word in visited:
continue
stack = [word]
cluster = []
visited.add(word)
while stack:
curr = stack.pop()
cluster.append((curr, frequencies[curr]))
for nxt in sorted(neighbors[curr]):
if nxt not in visited:
visited.add(nxt)
stack.append(nxt)
if len(cluster) > 1:
cluster.sort(key=lambda item: (-item[1], item[0]))
counts = [c for _, c in cluster]
groups.append(
{
"words": cluster,
"min_freq": min(counts),
"max_freq": max(counts),
"spread": max(counts) - min(counts),
}
)
groups.sort(key=lambda g: (-len(g["words"]), -g["max_freq"]))
elapsed = time.perf_counter() - start_time
return {
"groups": groups,
"comparisons_done": comparisons_done,
"total_possible_pairs": vocab_size * (vocab_size - 1) // 2,
"elapsed_seconds": elapsed,
"timed_out": timed_out,
}
raw_text = book_path.read_text(encoding="utf-8", errors="replace")
clean_text = prepare_quran_text(raw_text, strip_diacritics=True)
total_words, frequencies = brute_force_scan_and_count(clean_text)
print(f"Total words counted: {total_words:,}")
print(f"Unique word forms: {len(frequencies):,}\n")
results = find_similar_frequency_groups(
frequencies=frequencies,
tolerance=0, # 0 = exact frequency twins; increase to 1 or 2 for wider groups
max_seconds=30.0,
deep_search=True,
)
print(
f"Brute-force search finished in {results['elapsed_seconds']:.2f}s "
f"({results['comparisons_done']:,} / {results['total_possible_pairs']:,} pairs checked)"
)
print(f"Similar frequency groups found: {len(results['groups'])}\n")
for idx, grp in enumerate(results["groups"][:15], start=1):
preview = ", ".join(f"{w} ({c})" for w, c in grp["words"][:8])
extra = f" ... +{len(grp['words']) - 8} more" if len(grp["words"]) > 8 else ""
print(
f"Group {idx} [size={len(grp['words'])}, freq={grp['min_freq']}..{grp['max_freq']}]: "
f"{preview}{extra}"
)
Group 2 [size=1065, freq=9..190]: شيء (190), هذا (190), كفروا (189), كنتم (188), السماوات (182), الناس (182), لم (178), وهو (171) ... +1057 more
Group 3 [size=1015, freq=3..3]: آباءكم (3), آبائهم (3), آتيتم (3), آتيناكم (3), آذن (3), آناء (3), آنست (3), آياتك (3) ... +1007 more
Group 4 [size=618, freq=4..4]: آباءهم (4), آباؤهم (4), آبائكم (4), آتنا (4), آتيتموهن (4), آتيكم (4), آذان (4), آلهتكم (4) ... +610 more
Group 5 [size=400, freq=5..5]: آباؤكم (5), آتيناه (5), آلهتنا (5), أإله (5), أئمة (5), أبناء (5), أبناءهم (5), أتاهم (5) ... +392 more
Group 6 [size=288, freq=6..6]: آتاكم (6), آثارهم (6), أتاك (6), أتى (6), أجلهم (6), أجورهن (6), أخرجنا (6), أرأيت (6) ... +280 more
Group 7 [size=195, freq=7..7]: آباؤنا (7), آذانهم (7), آمنت (7), آمنين (7), أأنتم (7), أبانا (7), أتبع (7), أحدكم (7) ... +187 more
Group 8 [size=130, freq=8..8]: آتاهم (8), آخرين (8), آمنتم (8), أبت (8), أبواب (8), أخاهم (8), أريد (8), أعرض (8) ... +122 more
Group 9 [size=30, freq=214..416]: قال (416), إلى (405), لهم (373), يا (350), ومن (342), ثم (340), لكم (337), به (327) ... +22 more
Group 10 [size=5, freq=638..670]: على (670), إلا (664), ولا (658), وما (646), أن (638)
Group 11 [size=2, freq=966..1013]: ما (1013), إن (966)
Group 12 [size=2, freq=810..812]: لا (812), الذين (810)
Burada yeni gibi görünüyorsunuz. Eğer katılmak istiyorsanız düğmelerden birine tıklayınız.