import string
import nltk
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures
from nltk.collocations import TrigramCollocationFinder
from nltk.metrics import TrigramAssocMeasures
from nltk.corpus import PlaintextCorpusReader
from nltk.tokenize import word_tokenize

# NLTK-Ressourcen herunterladen (falls noch nicht geschehen)
nltk.download('punkt')

# Pfad zum Verzeichnis mit den Dateien
#corpus_root = 'F:\\Varlaam_Iasaf\\Ruthenisch-Text-Proccess\\txt_norm'
#corpus_root = 'F:\\Varlaam_Iasaf\\Polnisch-Text-Process\\txt_norm'
#corpus_root = 'F:\\Varlaam_Iasaf\\Latein-Text-Process\\txt_norm'
corpus_root = 'F:\\Varlaam_Iasaf\\Griechisch\process\\txt'
corpus_root = 'F:\\Schulung_Python\\examples\\txt'


# Erstellen des Corpus Readers für alle Dateien im Verzeichnis
wordlists = PlaintextCorpusReader(corpus_root, '.*')

# Liste von Ausschlusswörtern definieren
exclusion_words = set(['page', 'гл', 'варлаамѣ', 'иоасафѣ'])

# Gesamten Text aus allen Dateien zusammenführen
all_text = ""
for file in wordlists.fileids():
    all_text += wordlists.raw(file)

# Funktion, um Text zu bereinigen und Kollokationen zu finden
def find_collocations(text):
    # Entfernen von Satzzeichen
    #words = [word.lower() for word in word_tokenize(text) if word.isalpha()]
    words = [word.lower() for word in word_tokenize(text) if word.isalpha() and word.lower() not in exclusion_words]

    # Finden von Kollokationen im bereinigten Text
    #finder = BigramCollocationFinder.from_words(words)
    finder = TrigramCollocationFinder.from_words(words)
    scored = finder.score_ngrams(BigramAssocMeasures.raw_freq)

    # Sortieren der Kollokationen nach Häufigkeit
    return sorted(scored, key=lambda x: -x[1])

# Durchgehen jeder Datei und Analyse der Kollokationen
for file in wordlists.fileids():
    print(f"Kollokationen in Datei: {file}")

    # Text aus der Datei lesen
    text = wordlists.raw(file)

    # Kollokationen finden
    collocations = find_collocations(text)
    
    # Ausgabe der Top-Kollokationen (z.B. die Top 10)
    for collocation, freq in collocations[:100]:
        print(' '.join(collocation), freq)
    
    print("\n")

# Trigramm-Kollokationen im gesamten Text finden
trigram_collocations = find_collocations(all_text)

# Ausgabe der Top-Trigramm-Kollokationen (z.B. die Top 10)
print("Top Trigramm-Kollokationen im gesamten Corpus:")
for trigram, freq in trigram_collocations[:100]:
    print(' '.join(trigram), freq)
