Multitranslator – 6 tradutores com 1 clique

Multitranslator

O que é o Multitranslator? Como baixar, instalar e usar?

Baixe o app gratuitamente!


O app também pode ser baixado na Alemanha, não há risco nenhum! Fique tranquilo, todos os apps que publiquei e publicarei estão também de acordo com as leis alemãs. Tenho certeza que você já consultou pelo menos uma vez o Google Tradutor para traduzir uma frase em alemão para português, e, não ficou satisfeito com resultado. O que você fez então? Tentou o DeepL? Bing? Yeekit? Tencent? Argos? Provavelmente teve muito trabalho até conseguir o resultado desejado, né? A partir de hoje, seus problemas acabaram! Desenvolvi um aplicativo com o qual você pode traduzir qualquer texto, sem limite de caracteres com 6 tradutores ao mesmo tempo! O resultado é salvo automaticamente na pasta de documentos (Windows) como HTML e arquivo Excel (XLSX). E como não poderia deixar de ser, o app é 100% gratuito e bem simples de usar. Assista ao vídeo, baixe, instale e use o app. Compartilhe com seus amigos!

Baixe aqui:

https://www.dropbox.com/s/g5mtszb03hb8r92/multitranslator_setup.exe?dl=0

Este aplicativo traduz textos em alemão simultaneamente usando seguintes tradutores:

tencent
bing
argos
iciba
google
yeekit
deepl


Inicie o app e escolha qualquer arquivo txt/doc/pdf que você deseja traduzir.

Escolha o idioma para o qual deseja traduzir
(cuidado: talvez nem todos estejam disponíveis! Só testei o aplicativo com alemão -> português e alemão -> inglês)
O aplicativo traduz o texto simultaneamente (threads).
As configurações são muito conservadoras,
isso significa que pode demorar um pouco até que tudo seja traduzido (dependendo do tamanho do seu texto),
mas o bom é: seu IP não será bloqueado. O aplicativo também lida com o tamanho máximo
do texto traduzido, isso significa que você pode traduzir textos com mais do que o limite do tradutor
(por exemplo, 5.000 caracteres – limite do Google)
Depois que tudo estiver pronto, você verá o resultado como HTML.
Mais informações (em inglês no GITHUB)https://github.com/hansalemaos/multitranslator/

Código de fonte

multitranslator.py

import os
import shutil
from einfuehrung import einfuehrung
from bs4 import BeautifulSoup
from pytablewriter import ExcelXlsxTableWriter
from yeekit_tr import yeekit_tr
import translators as ts
import subprocess
import sys
from deep_translator import GoogleTranslator
from random import randrange as randomrandrange
from farbprinter.farbprinter import Farbprinter
from time import sleep, strftime
import pandas as pd
from CLASS_SUPERDICT2 import Superdict
from pytablewriter import HtmlTableWriter
import webbrowser
drucker = Farbprinter()
import kthread
from satzmetzger.satzmetzger import Satzmetzger
from regex import regex
tempfilename = 'xxxtempfilexxxxtranslation.txt'
tempfilenameout = 'xxxtempfilexxxxtranslation-tr.txt'
from ftlangdetect import detect
from sprache_waehlen import get_sprache
yeekitlimit=2000
sougolimit=2000
tencentlimit=500
binglimit =500
argoslimit = 500
icibalimit = 2000
googlelimit = 4000



def create_folder_in_documents_folder():
    timefolder = strftime("%Y_%m_%d_%H_%M_%S")
    documentsfolder = os.path.expanduser('~\\Documents')
    ganzerpfad = documentsfolder + '\\' + timefolder
    if not os.path.exists(ganzerpfad):
        try:
            os.makedirs(ganzerpfad)
            print(drucker.f.brightgreen.black.normal(f'Pfad: {ganzerpfad} erstellt!'))

        except:
            print(drucker.f.brightred.black.normal(f'Pfad: {ganzerpfad} konnte nicht erstellt werden!'))
            return None
    return ganzerpfad


def schlafen(min=4, max=10):
    min = min * 10
    max = max * 10
    try:
        sleep(randomrandrange(min, max) / 10)
    except:
        pass


def copy_file(src, dest):
    try:
        if os.path.isfile(src):
            dpath, dfile = os.path.split(dest)
            if not os.path.isdir(dpath):
                os.makedirs(dpath)
            try:
                shutil.copy2(src, dest)
                print(drucker.f.brightgreen.black.italic(f'The file {src} has just been copied to {dest}'))
                return True
            except Exception as Fehler:
                return False
    except:
        return False
    return False


def textsortieren(alleoriginaltexte, alleubertexte):
    resultdict = {}
    zaehler = 1
    for ori, uber in zip(alleoriginaltexte, alleubertexte):

        maximalezahl = int(regex.findall(r'^\s*0+(\d+)\s*\)\s+', ori.splitlines()[-1].strip())[0])
        for zahl in range(maximalezahl):
            resultdict[zaehler] = {}
            textsplittenoriginal = ori.splitlines()
            uebersetzter_text = uber.splitlines()
            zahlsuchen = str(zahl + 1).zfill(5)
            for orisatz in textsplittenoriginal:
                try:
                    detext = regex.findall(rf'^\s*{zahlsuchen}[^\n\r\v]+', orisatz)[0]
                    resultdict[zaehler]['de'] = detext
                    break
                except:
                    detext = ''
                    resultdict[zaehler]['de'] = detext
                    continue
            for ubersatz in uebersetzter_text:
                try:
                    uebersetztertext = regex.findall(rf'^\s*{zahlsuchen}[^\n\r\v]+', ubersatz)[0]
                    resultdict[zaehler]['andere'] = uebersetztertext
                    break
                except:
                    uebersetztertext = ''
                    resultdict[zaehler]['andere'] = uebersetztertext
                    continue
            zaehler = zaehler + 1
    return resultdict.copy()



def split_in_laenge(gesplittetertext, limit=5000, prozentsicherheit=10):
    gesplittetertext = [f'{x})\t\t{y}' for x, y in gesplittetertext]
    sicherheit = int(limit / prozentsicherheit)
    neueslimit = limit - sicherheit
    gesplittetertextneu = []
    laenge = 0
    zwischenergebnis = []
    for tt in gesplittetertext:
        if laenge >= neueslimit:
            laenge = 0
            zwischenergebnis.append(tt)
            gesplittetertextneu.append(zwischenergebnis.copy())
            zwischenergebnis.clear()
        if laenge < neueslimit:
            laenge = laenge + len(tt)
            zwischenergebnis.append(tt)
    if len(zwischenergebnis) > 0:
        gesplittetertextneu.append(zwischenergebnis)
    gesplittetertextneu = ['\n'.join(t) for t in gesplittetertextneu]
    return gesplittetertextneu.copy()


def get_file_path(datei):
    pfad = sys.path
    pfad = [x.replace('/', '\\') + '\\' + datei for x in pfad]
    exists = []
    for p in pfad:
        if os.path.exists(p):
            exists.append(p)
    return list(dict.fromkeys(exists))

def write_text_to_file(text):
    metzgerle = Satzmetzger()
    gesplittetertext =metzgerle.zerhack_den_text(text)
    gesplittetertext = [(str(ini+1).zfill(5),x) for ini,x in enumerate(gesplittetertext)]
    ganzerstring = ''
    for saetze in gesplittetertext:
        ganzerstring = ganzerstring + saetze[0] + ')'+ '\t\t' + saetze[1] + '\n\n'
    with open(tempfilename,  mode='w', encoding='utf-8') as f:
        f.write(ganzerstring)
    return gesplittetertext


def write_results_to_textfile(filepath, uebersetztertext):
    with open(filepath,  mode='w', encoding='utf-8') as f:
        f.write(str(uebersetztertext))


def create_symlink(dateipfad, symlink, withending=False):
    'use like this: create_symlink(r"c:\folder oder file with\shi--y name", "nicename", withending=False)'
    if not os.path.isdir(dateipfad):
        dateipfadendung = dateipfad.split('.')[-1]
        os.close(os.open(dateipfad, os.O_CREAT))
    try:
        if os.path.islink(symlink) is True:
            os.remove(symlink)
    except:
        pass
    if withending is True:
        symlink = symlink + '.' + dateipfadendung
    os.symlink(dateipfad, symlink)
    return symlink

def translate_text():
    data =''
    test = subprocess.run(['deepl-tr-pp', '-p', tempfilename, '-f', 'de', '-t', outputlanguage, '--nooutput-docx'], capture_output=True)
    try:
        filename = regex.findall('File written to(.*\.txt)' , str(test.stderr))
        filename = filename[0].strip().replace('\\\\', '\\')
    except Exception as Fehler:
        filename = tempfilenameout
    try:
        with open(filename, encoding='utf-8') as f:
            data = f.read()
        os.remove(filename)
        try:
            os.remove(textfile_deepl_resultate)
        except:
            pass
        write_results_to_textfile(textfile_deepl_resultate, data)
    except Exception as Fehler:
        pass
    return data

def mit_iciba():
    global iciba_resultate
    auf5000 = split_in_laenge(allesaetzeuebersetzen, limit=binglimit, prozentsicherheit=20)
    alleergebnisse =[]

    for ini,wort in enumerate(auf5000):
        try:
            uebersetzter_text = ts.iciba(wort, from_language='de', to_language=outputlanguage)
            alleergebnisse.append(uebersetzter_text)
        except Exception as Fehler:
            pass
        schlafen()
    iciba_resultate = textsortieren(alleoriginaltexte=auf5000, alleubertexte=alleergebnisse)
    try:
        os.remove(textfile_iciba_resultate)
    except:
        pass
    write_results_to_textfile(textfile_iciba_resultate ,alleergebnisse)


def mit_argos():
    global argos_resultate
    auf5000 = split_in_laenge(allesaetzeuebersetzen, limit=binglimit, prozentsicherheit=20)
    alleergebnisse =[]

    for ini,wort in enumerate(auf5000):
        try:
            uebersetzter_text = ts.argos(wort, from_language='de', to_language=outputlanguage)
            alleergebnisse.append(uebersetzter_text)
        except Exception as Fehler:
            pass
        schlafen()
    argos_resultate = textsortieren(alleoriginaltexte=auf5000, alleubertexte=alleergebnisse)
    try:
        os.remove(textfile_argos_resultate)
    except:
        pass
    write_results_to_textfile(textfile_argos_resultate ,alleergebnisse)





def mit_bing():
    global bing_resultate
    auf5000 = split_in_laenge(allesaetzeuebersetzen, limit=binglimit, prozentsicherheit=20)
    alleergebnisse =[]

    for ini,wort in enumerate(auf5000):
        try:
            uebersetzter_text = ts.bing(wort, from_language='de', to_language=outputlanguage)
            alleergebnisse.append(uebersetzter_text)
        except Exception as Fehler:
            pass
        schlafen()
    bing_resultate = textsortieren(alleoriginaltexte=auf5000, alleubertexte=alleergebnisse)
    try:
        os.remove(textfile_bing_resultate )
    except:
        pass
    write_results_to_textfile(textfile_bing_resultate  ,alleergebnisse)


def mit_tencent():
    global tencent_resultate
    auf5000 = split_in_laenge(allesaetzeuebersetzen, limit=tencentlimit, prozentsicherheit=20)
    alleergebnisse =[]

    for ini,wort in enumerate(auf5000):
        try:
            uebersetzter_text = ts.tencent(wort, from_language='de', to_language=outputlanguage)
            alleergebnisse.append(uebersetzter_text)
        except Exception as Fehler:
            pass
        schlafen()
    tencent_resultate = textsortieren(alleoriginaltexte=auf5000, alleubertexte=alleergebnisse)
    try:
        os.remove(textfile_tencent_resultate )
    except:
        pass
    write_results_to_textfile(textfile_tencent_resultate  ,alleergebnisse)


def mit_yeekit():
    global yeekit_resultate
    auf5000 = split_in_laenge(allesaetzeuebersetzen, limit=yeekitlimit, prozentsicherheit=20)
    alleergebnisse =[]

    for ini,wort in enumerate(auf5000):
        try:
            uebersetzter_text = yeekit_tr(wort,from_lang='de', to_lang=outputlanguage)
            alleergebnisse.append(uebersetzter_text)
        except Exception as Fehler:
            pass
        schlafen()
    yeekit_resultate = textsortieren(alleoriginaltexte=auf5000, alleubertexte=alleergebnisse)
    try:
        os.remove(textfile_yeekit_resultate  )
    except:
        pass
    write_results_to_textfile(textfile_yeekit_resultate   ,alleergebnisse)


def mit_google_ubersetzen():
    global google_resultate
    auf5000 = split_in_laenge(allesaetzeuebersetzen, limit=googlelimit, prozentsicherheit=10)
    alleergebnisse =[]

    for ini,wort in enumerate(auf5000):
        try:
            uebersetzter_text = GoogleTranslator(
                source="de", target=outputlanguage
            ).translate(wort)
            alleergebnisse.append(uebersetzter_text)

        except Exception as Fehler:
            pass
        schlafen()
    google_resultate = textsortieren(alleoriginaltexte=auf5000, alleubertexte=alleergebnisse)
    try:
        os.remove(textfile_google_resultate   )
    except:
        pass
    write_results_to_textfile(textfile_google_resultate    ,alleergebnisse)



def text_allestarten(ubersetzer):
    global deepl_resultate
    if ubersetzer == 'deepl':
        text = translate_text()
        text_lines = text.splitlines()
        resultat_original = []
        resultat_uebersetzungen = []
        for ini, line in enumerate(text_lines):
            deepl_resultate[ini] = {}
            lineformatiert = regex.sub(r'^\d+\)\s*', '', line)
            result = detect(text=lineformatiert, low_memory=False)
            if result['lang'] == 'de':
                deepl_resultate[ini]['de'] = line
                continue
            deepl_resultate[ini]['andere'] = line
        return resultat_original, resultat_uebersetzungen

    if ubersetzer == 'google':
        mit_google_ubersetzen()
    if ubersetzer == 'tencent':
        mit_tencent()
    if ubersetzer == 'argos':
        mit_argos()
    if ubersetzer == 'iciba':
        mit_iciba()
    if ubersetzer == 'bing':
        mit_bing()
    if ubersetzer == 'yeekit':
        mit_yeekit()

def read_textfiles(datei):
    with open(datei, encoding='utf-8') as f:
        data = f.read()


def write_to_excel(df, filename):
    datenframe = df.copy()
    datenframe['original'] = df.index
    writer = ExcelXlsxTableWriter()
    writer.from_dataframe(datenframe)
    writer.dump(filename)


def write_to_html(df, filename):
    datenframe = df.copy()
    datenframe['original'] = df.index
    writer = HtmlTableWriter()
    writer.from_dataframe(datenframe)
    coloredhtml = regex.sub(r'<thead>', r'<thead style="background-color:#ffff00">', str(writer), regex.DOTALL)
    coloredhtmllist = coloredhtml.splitlines()
    fertightml = []
    zaehler = 0
    for ini, line in enumerate(coloredhtmllist):
        if '<tr>' in line:
            if zaehler == 0:
                fertightml.append(line)
                zaehler = zaehler + 1
                continue
            if zaehler % 2 == 0:
                line = line.replace('<tr>', '<tr style="background-color:#ffff99">')
            fertightml.append(line)
            zaehler = zaehler + 1
            continue
        fertightml.append(line)

    fertightml = '''<h1 style="background-color:black;color:red;font-size:36px;">&ensp;&ensp;&ensp;&ensp;&ensp;Made by&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;<a href="https://www.queroestudaralemao.com.br/" style="background-color:black;color:yellow;font-size:48px;">queroestudaralemao.com.br</a></h1>''' + '\n'.join(fertightml)
    write_to_file(filepath=filename, text=fertightml)


def filename_from_text(text, ending='txt', length=30):
    dateiname = regex.sub(r'\W+', '_', text)
    dateiname = dateiname.strip('_')
    dateiname = dateiname.strip()
    dateiname = dateiname[:length]
    dateiname = dateiname +'.' + ending
    dateiname = dateiname.lower()
    return dateiname

def write_to_file(filepath, text):
    with open(filepath, encoding='utf-8', mode='w') as f:
        if isinstance(text, list):
            for l in text:
                try:
                    f.write(str(l))
                    f.write('\n')
                except:
                    continue
        if isinstance(text, str):
            f.write(str(text))
def txtdateien_lesen(text):
    try:
        dateiohnehtml = (
            b"""<!DOCTYPE html><html><body><p>""" + text + b"""</p></body></html>"""
        )
        soup = BeautifulSoup(dateiohnehtml, "html.parser")
        soup = soup.text
        return soup.strip()
    except Exception as Fehler:
        pass


def get_text():
    p = subprocess.run(get_file_path(r"Everything2TXT.exe")[0], capture_output=True)
    ganzertext = txtdateien_lesen(p.stdout)
    return ganzertext

def removetempfiles():
    try:
        os.remove(textfile_tencent_resultate)
    except:
        pass
    try:
        os.remove(textfile_bing_resultate)
    except:
        pass
    try:
        os.remove(textfile_argos_resultate)
    except:
        pass
    try:
        os.remove(textfile_iciba_resultate)
    except:
        pass
    try:
        os.remove(textfile_deepl_resultate)
    except:
        pass
    try:
        os.remove(textfile_google_resultate)
    except:
        pass
    try:
        os.remove(textfile_sogou_resultate)
    except:
        pass
    try:
        os.remove(textfile_yeekit_resultate)
    except:
        pass
    try:
        os.remove(tempfilename)
    except:
        pass

def find_same_elements_in_list(*args):
    """Examples: print(find_same_elements_in_list([1, 2, 3], [1, 2, 3, 4, 5], [2, 3, 4]))
        print(find_same_elements_in_list([1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 3, 4], [1, 4]))
        ne = find_same_elements_in_list([[1, 2], [3, 4]], [[1, 2]])
        print(ne)
        ne2 = find_same_elements_in_list([[1, 2], [3, 4]], [[1, 2]], [44,55, [1,2]])
        print(ne2)

        output:
        [2, 3]
        [1, 4]
        [[1, 2]]
        [[1, 2]]

        :param args: list
        :return : list
    """
    try:
        a_set = set(args[0])
        b_set = set(args[1])
        matches = a_set.intersection(b_set)
        if len(args) > 2:
            otherlists = list(args[2:])
            for other in otherlists:
                c_set = set(other)
                matches = matches.intersection(c_set)
        matches = list(matches)
        return matches
    except Exception as Fehler:
        ergebnisse = []
        listealsstring = []
        for arg in args:
            nestedlist = [str(x) for x in arg]
            listealsstring.append(nestedlist.copy())
        a_set = set(listealsstring[0])
        b_set = set(listealsstring[1])
        matches = a_set.intersection(b_set)
        if len(listealsstring) > 2:
            otherlists = listealsstring[2:]
            for other in otherlists:
                c_set = set(other)
                matches = matches.intersection(c_set)
            matches = list(matches)
        for arg in args:
            for li in arg:
                if str(li) in matches:
                    ergebnisse.append(li)
        tempstringlist = {}
        for ergi in ergebnisse:
            tempstringlist[str(ergi)] = ergi
        endliste = [tempstringlist[key] for key in tempstringlist.keys()]
        return endliste.copy()

def get_second_value(x):
    try:
        return x[1]
    except:
        return x
def find_different_elements_in_list(*args):
    """
    Examples:  print(find_different_elements_in_list([3, 1, 2, 4], [1, 2, 54, 99, 4], [33, 1, 2, 3]))
    print(find_different_elements_in_list([[1,2], [332,4]], [[55,55,1], [1,2],[33,44] ], [[22,4], [1,2]]))

    output:
    [54, 99, 33]
    [[332, 4], [55, 55, 1], [33, 44], [22, 4]]

    :param args: list
    :return : list
    """
    gleicheelemente = find_same_elements_in_list(*args)
    gleicheelemente =[str(x) for x in gleicheelemente]
    ergebnisse = []
    for listen in list(args):
        for element in listen:
            if str(element) not in gleicheelemente:
                ergebnisse.append(element)
    ergebnisse2 = [str(x) for x in ergebnisse]
    ergebnisse_zaehlen = [[ergebnisse2.count(str(x)),x] for x in ergebnisse]
    einzelneergebnisse = [x[1] for x in ergebnisse_zaehlen if x[0] == 1]
    return einzelneergebnisse

if __name__ == "__main__":
    einfuehrung('Translatornator')
    outputlanguage = get_sprache('\nBitte Zielsprache eingeben:\n')[1]

    text = get_text()
    write_to_file(filepath=tempfilename, text=text)

    foldername = create_folder_in_documents_folder()
    filenamesave_txt = str(foldername) + '\\' + filename_from_text(text, ending='txt', length=30)
    filenamesave_xlsx =  str(foldername) + '\\' +filename_from_text(text, ending='xlsx', length=30)
    filenamesave_html =  str(foldername) + '\\' +filename_from_text(text, ending='html', length=30)


    textfile_tencent_resultate = 'tencent_resultate.txt'
    textfile_bing_resultate = 'bing_resultate.txt'
    textfile_argos_resultate = 'argos_resultate.txt'
    textfile_iciba_resultate = 'iciba_resultate.txt'
    textfile_deepl_resultate = 'deepl_resultate.txt'
    textfile_google_resultate = 'google_resultate.txt'
    textfile_sogou_resultate = 'sogou_resultate.txt'
    textfile_yeekit_resultate = 'yeekit_resultate.txt'

    tencent_resultate = {}
    bing_resultate = {}
    argos_resultate = {}
    iciba_resultate = {}
    deepl_resultate = {}
    google_resultate = {}
    yeekit_resultate ={}
    allesaetzeuebersetzen = write_text_to_file(text)
    alleuebersetzer = ['deepl', 'google', 'tencent', 'bing', 'argos', 'iciba', 'yeekit']

    allethreads = []
    for aktion in alleuebersetzer:
        allethreads.append(
            kthread.KThread(
                target=text_allestarten,
                name=aktion,
                args=(aktion,),
            )
        )
    gestartet = [los.start() for los in allethreads]
    nochamleben = [(t.name, t.is_alive()) for t in allethreads]
    nuramleben = [x[1] for x in nochamleben if x[1] == True]
    while any(nuramleben):
        nochamleben = [(t.name, t.is_alive()) for t in allethreads]
        for thr in nochamleben:
            if thr[1] is True:
                print(drucker.f.black.brightred.italic(f"{thr[0]} übersetzt noch!"))
            if thr[1] is False:
                print(drucker.f.black.brightgreen.italic(f"{thr[0]} ist fertig!"))
        sleep(2)
        nuramleben = [x[1] for x in nochamleben if x[1] == True]

    alleinfos = [tencent_resultate,
                    bing_resultate,
                    argos_resultate,
                    iciba_resultate,
                    google_resultate,
                    yeekit_resultate]

    dictzumeinlesen = Superdict()
    for ini,di in enumerate(alleinfos):
        for d in di.keys():
            try:
                if any(di[d]['de']):
                    deutsch = regex.sub(r'^\s*\d{5}\)\s+', '', di[d]['de']).strip()
                    sprache2 = regex.sub(r'^\s*\d{5}\)?\s*', '', di[d]['andere']).strip()
                    einfuegen = (ini, sprache2)
                    if einfuegen in dictzumeinlesen[deutsch] :
                        continue
                    dictzumeinlesen[deutsch] = (ini, sprache2)
            except:
                pass

    neuesdict = Superdict()
    for key, item in dictzumeinlesen.items():
        try:
            if len(item) == 6:
                neuesdict[key] = item
                continue
            if len(item) >= 7:
                checkenob6 =[]
                checkenob6zahl =[]
                rausmachen = item
                transp = [list(xaaa) for xaaa in zip(*rausmachen)][0]
                wegmachen = [[x[0], x[1], len(x[1]), transp.count(x[0])] for x in rausmachen]
                drucker.p.black.red.bold(wegmachen)
                wegmachen = [(x[0], x[1]) for x in wegmachen if x[3] == 1 or x[2] != 0]
                drucker.p.black.blue.bold(wegmachen)

                for weg in wegmachen:
                    if weg[0] not in checkenob6zahl:
                        checkenob6.append(weg)
                        checkenob6zahl.append(weg[0])
                        drucker.p.blue.yellow.bold(checkenob6zahl)
                neuesdict[key] = checkenob6.copy()
                continue
            if len(item) <6:
                neueliste = []
                checkliste = [0,1,2,3,4,5]
                reinmachen = item
                transp = [list(xaaa) for xaaa in zip(*reinmachen)][0]
                drucker.p.black.brightblue.italic(transp)

                fehlt = find_different_elements_in_list(checkliste, transp)
                drucker.p.black.brightmagenta.italic(fehlt)
                for rein in reinmachen:
                    neueliste.append(rein)
                if any(fehlt):
                    for f in fehlt:
                        neueliste.append((f, ''))
                neueliste.sort()
                drucker.p.yellow.black.italic(neueliste)
                neuesdict[key] = neueliste.copy()
                continue
        except Exception as Fehler:
            print(Fehler)
    neuesdict2 = Superdict()
    for key, item in neuesdict.items():
        try:
            if len(item) == 6:
                neuesdict2[key] = item
                continue
            if len(item) >= 7:
                checkenob6 =[]
                checkenob6zahl =[]
                rausmachen = item
                transp = [list(xaaa) for xaaa in zip(*rausmachen)][0]
                wegmachen = [[x[0], x[1], len(x[1]), transp.count(x[0])] for x in rausmachen]
                drucker.p.black.red.bold(wegmachen)
                wegmachen = [(x[0], x[1]) for x in wegmachen if x[3] == 1 or x[2] != 0]
                drucker.p.black.blue.bold(wegmachen)

                for weg in wegmachen:
                    if weg[0] not in checkenob6zahl:
                        checkenob6.append(weg)
                        checkenob6zahl.append(weg[0])
                        drucker.p.blue.yellow.bold(checkenob6zahl)
                neuesdict2[key] = checkenob6.copy()
                continue
            if len(item) <6:
                neueliste = []
                checkliste = [0,1,2,3,4,5]
                reinmachen = item
                transp = [list(xaaa) for xaaa in zip(*reinmachen)][0]
                drucker.p.black.brightblue.italic(transp)

                fehlt = find_different_elements_in_list(checkliste, transp)
                drucker.p.black.brightmagenta.italic(fehlt)
                for rein in reinmachen:
                    neueliste.append(rein)
                if any(fehlt):
                    for f in fehlt:
                        neueliste.append((f, ''))
                neueliste.sort()
                drucker.p.yellow.black.italic(neueliste)
                neuesdict2[key] = neueliste.copy()
                continue
        except Exception as Fehler:
            print(Fehler)
    df = pd.DataFrame(neuesdict2.to_dict())
    df = df.T.copy()
    colohnedeepl =  ['tencent', 'bing', 'argos', 'iciba', 'google', 'yeekit']
    try:
        df.columns =colohnedeepl
    except:
        pass

    hinzufuegendeepl = []
    zwischen = []
    for key, item in deepl_resultate.items():

        try:
            zwischen.append(item['de'][7:])

        except:
            pass
        try:
            hinzufuegen = regex.sub(r'^\s*\d+\)?\s*', '', item['andere'])
            zwischen.append(hinzufuegen)
            hinzufuegendeepl.append(zwischen.copy())
            zwischen.clear()

            # print(key)
        except:
            pass
    for key, value in hinzufuegendeepl:
        drucker.p.black.brightmagenta.italic(value)
        df.at[key, 'deepl'] = value


    for col in colohnedeepl:
        df[col] = df[col].apply(get_second_value)

    try:
        write_to_excel(df, filenamesave_xlsx)
        write_to_html(df, filenamesave_html)
    except Exception as Fehler:
        print(Fehler)
    drucker.f.black.brightmagenta.normal('Excel file saved:\t\t') + drucker.f.black.brightmagenta.negative(filenamesave_xlsx)
    drucker.f.black.brightmagenta.normal('HTML file saved:\t\t') + drucker.f.black.brightmagenta.negative(filenamesave_html)
    try:
        webbrowser.open(filenamesave_html)
    except:
        pass
    input(drucker.f.black.brightred.bold('ENTER drücken, um das Programm zu beenden.'))


sprache_auswaehlen.py

import pandas as pd
from farbprinter.farbprinter import Farbprinter
drucker = Farbprinter()
import re
def get_sprache(textanzeigen):
    df = pd.read_pickle('SPRACHENWAEHLEN_DF.PKL')
    dfa = []
    fehlerdrucken=False
    fehlermeldung = ''
    eingabe =''
    while not any(dfa):
        try:
            drucker.p_pandas_list_dict(df)
            if fehlerdrucken is True:
                print(drucker.f.brightred.black.bold(f'n{eingabe} konnte nicht verstanden werden!nFehler:{fehlermeldung}nBitte noch einmal probierenn'))
            eingabe = input(drucker.f.black.brightyellow.bold(f"n{textanzeigen}. nGültige Eingaben für Deutsch sind beispielsweise: ['52', 'German', 'de', 'ger', 'deu']nn"))
            eingabe=eingabe.strip()
            if len(eingabe) == 2 and not eingabe.isnumeric():
                dfa = df.loc[df.iso_6391.str.contains(rf'^{eingabe}$', regex=True)].iloc[0].to_list()
                continue
            elif len(eingabe) == 3 and not eingabe.isnumeric():
                try:
                    dfa = df.loc[df.iso_6392.str.contains(rf'^{eingabe}$', regex=True)].iloc[0].to_list()
                    continue
                except:
                    dfa = df.loc[df.iso_6393.str.contains(rf'^{eingabe}$', regex=True)].iloc[0].to_list()
                    continue
            try:
                dfa = df.loc[eingabe].to_list()
                continue
            except:
                dfa = df.loc[df.language.str.contains(rf'^{eingabe}$', regex=True, flags=re.IGNORECASE)].iloc[0].to_list()
        except Exception as Fehler:
            fehlermeldung=Fehler
            fehlerdrucken=True
            continue
    print(drucker.f.brightgreen.black.bold(f'nGewählte Sprache:n{dfa}n'))
    return dfa

einfuehrung.py

from maximize_console import *
from farbprinter.farbprinter import Farbprinter
drucker = Farbprinter()
from add_color_print import add_color_print_to_regedit, updates_quero_estudar_alemao
def einfuehrung(name):
    print(1000 * "n")
    maximize_console(lines=30000)
    add_color_print_to_regedit()
    colorfunctionslogo = [drucker.f.black.red.normal, drucker.f.black.brightyellow.normal]
    drucker.p_ascii_front_on_flag_with_border(
        text=name,
        colorfunctions=colorfunctionslogo,
        bordercolorfunction=drucker.f.brightgreen.black.italic,
        font="slant",
        width=1000,
        offset_from_left_side=5,
        offset_from_text=15,
    )
    colorfunctionspage = [
        drucker.f.black.brightwhite.normal,
        drucker.f.black.brightgreen.normal,
    ]
    drucker.p_ascii_front_on_flag_with_border(
        text="www . queroestudaralemao . com . br",
        colorfunctions=colorfunctionspage,
        bordercolorfunction=drucker.f.brightgreen.black.negative,
        font="slant",
        width=1000,
        offset_from_left_side=1,
        offset_from_text=1,
    )
    updates_quero_estudar_alemao()


add_color_print.py

from json import loads as jsonloads
from os import name as osname
from sys import exit as sysexit
from textwrap import TextWrapper
from random import choice
from requests import get as requestsget
from farbprinter.farbprinter import Farbprinter

windowsrechner = osname == "nt"
from winregistry import WinRegistry
from winreg import HKEY_CURRENT_USER, KEY_READ, REG_DWORD

linebreakx = 50
wrapper = TextWrapper(width=linebreakx)
drucker = Farbprinter()
jsonqueroestudaralemao = "https://www.queroestudaralemao.com.br/wp-content/uploads/updateinformatioen/update.json"
logo_auswahl = auswahlliste = [
    drucker.f.brightred.black.bold,
    drucker.f.black.brightred.bold,
    drucker.f.yellow.black.bold,
    drucker.f.brightyellow.black.bold,
]
REGEDITPATH = r"HKEY_CURRENT_USER\Console"
regedit_success = "I think, it has worked out! Let's start"
virtualterminalregedit = "VirtualTerminalLevel"
able_to_see_col_text = "Everything is configured right! You should be able to see colored text! Please restart the app if you can't see colored text"
regedit_is_zero = "HKEY_CURRENT_USER\Console\VirtualTerminalLevel is set to 0! I will try to change it to 1 so that you can read colored text!"
regeditfail = """I was unable to change the Registry!\n Let\'s try it anyway!\n If you can\'t read the text in the terminal, add this to your Windows Registry:\n\n[HKEY_CURRENT_USER\Console]\n
"VirtualTerminalLevel"=dword:00000001"""
try_to_create_key = "HKEY_CURRENT_USER\Console\VirtualTerminalLevel not found! I will try to create it so that you can see colored text"


def add_color_print_to_regedit():
    if windowsrechner:
        try:
            with WinRegistry() as client:
                try:

                    regedit_entry = client.read_entry(
                        REGEDITPATH, virtualterminalregedit
                    )
                    if int(regedit_entry.value) == 1:
                        print(drucker.f.black.green.negative(able_to_see_col_text))
                        return True
                    if int(regedit_entry.value) == 0:
                        print(drucker.f.black.brightyellow.negative(regedit_is_zero))
                        try:
                            client.write_entry(
                                REGEDITPATH,
                                virtualterminalregedit,
                                value=1,
                                reg_type=REG_DWORD,
                            )
                            print(drucker.f.black.green.negative(regedit_success))
                        except:
                            print(drucker.f.black.brightred.negative(regeditfail))
                            return False
                except:
                    print(drucker.f.black.brightyellow.negative(try_to_create_key))
                    try:
                        client.write_entry(
                            REGEDITPATH,
                            "VirtualTerminalLevel",
                            value=1,
                            reg_type=REG_DWORD,
                        )
                        print(drucker.f.black.green.negative(regedit_success))

                        return True
                    except:
                        print(drucker.f.black.brightred.negative(regeditfail))
                        return False
        except:
            print(
                drucker.f.black.brightred.negative(
                    "Error checking if VirtualTerminalLevel is set to 1"
                )
            )


def updates_quero_estudar_alemao():
    choice(auswahlliste)("made by queroestudaralemao.com.br")
    print(
        drucker.f.black.brightblue.bold(
            "\n         Updates from https://www.queroestudaralemao.com.br :\n\n"
        )
    )

    jsoninhalt = requestsget(jsonqueroestudaralemao)
    j = jsonloads(jsoninhalt.text)

    for key, value in j.items():
        neuigkeitendatum = drucker.f.cyan.brightwhite.italic(
            f"""         {key} - News from    """.ljust(20).rjust(20)
        )
        print(neuigkeitendatum, end=" ")
        print(
            drucker.f.black.brightwhite.negative(f'       {value["autor"]}:        '),
            end=" ",
        )
        print(
            drucker.f.brightwhite.blue.negative(f'       {value["datum"]}:        '),
            end=" ",
        )
        neuigkeitenwrap = wrapper.wrap(text=value["neuigkeiten"])
        print("\n")
        for satz in neuigkeitenwrap:
            print(drucker.f.black.brightyellow.bold("     "), end="")
            ausfuellen = (70 - len(satz)) * " "
            print(
                drucker.f.black.brightyellow.bold(f"   {satz}   {ausfuellen}"), end="\n"
            )
        if value["online"] == "0":
            print(value["nachricht"])
            sysexit()
        print("\n")







add_color_print_reg.py

from json import loads as jsonloads
from os import name as osname
from sys import exit as sysexit
from textwrap import TextWrapper
from random import choice
from requests import get as requestsget
from farbprinter.farbprinter import Farbprinter

windowsrechner = osname == "nt"
from winregistry import WinRegistry
from winreg import HKEY_CURRENT_USER, KEY_READ, REG_DWORD

linebreakx = 50
wrapper = TextWrapper(width=linebreakx)
drucker = Farbprinter()
jsonqueroestudaralemao = "https://www.queroestudaralemao.com.br/wp-content/uploads/updateinformatioen/update.json"
logo_auswahl = auswahlliste = [
    drucker.f.brightred.black.bold,
    drucker.f.black.brightred.bold,
    drucker.f.yellow.black.bold,
    drucker.f.brightyellow.black.bold,
]
REGEDITPATH = r"HKEY_CURRENT_USERConsole"
regedit_success = "I think, it has worked out! Let's start"
virtualterminalregedit = "VirtualTerminalLevel"
able_to_see_col_text = "Everything is configured right! You should be able to see colored text! Please restart the app if you can't see colored text"
regedit_is_zero = "HKEY_CURRENT_USERConsoleVirtualTerminalLevel is set to 0! I will try to change it to 1 so that you can read colored text!"
regeditfail = """I was unable to change the Registry!n Let's try it anyway!n If you can't read the text in the terminal, add this to your Windows Registry:nn[HKEY_CURRENT_USERConsole]n
"VirtualTerminalLevel"=dword:00000001"""
try_to_create_key = "HKEY_CURRENT_USERConsoleVirtualTerminalLevel not found! I will try to create it so that you can see colored text"


def add_color_print_to_regedit():
    if windowsrechner:
        try:
            with WinRegistry() as client:
                try:

                    regedit_entry = client.read_entry(
                        REGEDITPATH, virtualterminalregedit
                    )
                    if int(regedit_entry.value) == 1:
                        print(drucker.f.black.green.negative(able_to_see_col_text))
                        return True
                    if int(regedit_entry.value) == 0:
                        print(drucker.f.black.brightyellow.negative(regedit_is_zero))
                        try:
                            client.write_entry(
                                REGEDITPATH,
                                virtualterminalregedit,
                                value=1,
                                reg_type=REG_DWORD,
                            )
                            print(drucker.f.black.green.negative(regedit_success))
                        except:
                            print(drucker.f.black.brightred.negative(regeditfail))
                            return False
                except:
                    print(drucker.f.black.brightyellow.negative(try_to_create_key))
                    try:
                        client.write_entry(
                            REGEDITPATH,
                            "VirtualTerminalLevel",
                            value=1,
                            reg_type=REG_DWORD,
                        )
                        print(drucker.f.black.green.negative(regedit_success))

                        return True
                    except:
                        print(drucker.f.black.brightred.negative(regeditfail))
                        return False
        except:
            print(
                drucker.f.black.brightred.negative(
                    "Error checking if VirtualTerminalLevel is set to 1"
                )
            )


def updates_quero_estudar_alemao():
    choice(auswahlliste)("made by queroestudaralemao.com.br")
    print(
        drucker.f.black.brightblue.bold(
            "n         Updates from https://www.queroestudaralemao.com.br :nn"
        )
    )

    jsoninhalt = requestsget(jsonqueroestudaralemao)
    j = jsonloads(jsoninhalt.text)

    for key, value in j.items():
        neuigkeitendatum = drucker.f.cyan.brightwhite.italic(
            f"""         {key} - News from    """.ljust(20).rjust(20)
        )
        print(neuigkeitendatum, end=" ")
        print(
            drucker.f.black.brightwhite.negative(f'       {value["autor"]}:        '),
            end=" ",
        )
        print(
            drucker.f.brightwhite.blue.negative(f'       {value["datum"]}:        '),
            end=" ",
        )
        neuigkeitenwrap = wrapper.wrap(text=value["neuigkeiten"])
        print("n")
        for satz in neuigkeitenwrap:
            print(drucker.f.black.brightyellow.bold("     "), end="")
            ausfuellen = (70 - len(satz)) * " "
            print(
                drucker.f.black.brightyellow.bold(f"   {satz}   {ausfuellen}"), end="n"
            )
        if value["online"] == "0":
            print(value["nachricht"])
            sysexit()
        print("n")

maximize_console.py

import os
import ctypes
import msvcrt
import subprocess
from ctypes import wintypes

kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
user32 = ctypes.WinDLL("user32", use_last_error=True)
SW_MAXIMIZE = 3
kernel32.GetConsoleWindow.restype = wintypes.HWND
kernel32.GetLargestConsoleWindowSize.restype = wintypes._COORD
kernel32.GetLargestConsoleWindowSize.argtypes = (wintypes.HANDLE,)
user32.ShowWindow.argtypes = (wintypes.HWND, ctypes.c_int)


def maximize_console(lines=None):
    fd = os.open("CONOUT$", os.O_RDWR)
    try:
        hCon = msvcrt.get_osfhandle(fd)
        max_size = kernel32.GetLargestConsoleWindowSize(hCon)
        if max_size.X == 0 and max_size.Y == 0:
            raise ctypes.WinError(ctypes.get_last_error())
    finally:
        os.close(fd)
    cols = max_size.X
    hWnd = kernel32.GetConsoleWindow()
    if cols and hWnd:
        if lines is None:
            lines = max_size.Y
        else:
            lines = max(min(lines, 9999), max_size.Y)
        subprocess.check_call("mode.com con cols={} lines={}".format(cols, lines))
        user32.ShowWindow(hWnd, SW_MAXIMIZE)

CLASS_SUPERDICT2.py

import ast
import copy
import math
import regex
import regex as re
from pprint import pprint as pp
import json
import pandas as pd
import re
import numpy as np

def isnan(wert, nanzurueck=False, debug=False):
    allenanvalues = ['<NA>', '<NAN>', '<nan>', 'np.nan', 'NoneType', 'None', '-1.#IND', '1.#QNAN', '1.#IND', '-1.#QNAN',
                     '#N/A N/A', '#N/A', 'N/A', 'n/a', 'NA', '', '#NA', 'NULL', 'null', 'NaN', '-NaN', 'nan', '-nan']
    try:
        if pd.isna(wert) is True:
            if nanzurueck is True: return np.nan
            return True
    except Exception as Fehler:
        if debug is True: print(Fehler)

    try:
        if pd.isnull(wert) is True:
            if nanzurueck is True: return np.nan
            return True
    except Exception as Fehler:
        if debug is True: print(Fehler)

    try:
        if math.isnan(wert) is True:
            if nanzurueck is True: return np.nan
            return True
    except Exception as Fehler:
        if debug is True: print(Fehler)

    try:
        if wert is None:
            return True
    except Exception as Fehler:
        if debug is True: print(Fehler)

    for allaaa in allenanvalues:
        try:
            nanda = regex.findall(str(fr'^\s*{wert}\s*$'), allaaa)
            if any(nanda):
                return True
        except Exception as Fehler:
            if debug is True: print(Fehler)
            return False

    return False


def flattenlist_neu_ohne_tuple(iterable, nanundleerweg=False):
    """24.10"""

    if nanundleerweg is True:
        if isinstance(iterable, list):
            try:
                iterable = [i for i in iterable if isnan(i) is False]
            except:
                pass

    def iter_flatten(iterable):
        it = iter(iterable)
        for e in it:

            if isinstance(e, list):
                for f in iter_flatten(e):
                    yield f
            else:
                yield e


    a = [i for i in iter_flatten(iterable)]
    if nanundleerweg is True:

        try:
            a = [i for i in a if isnan(i) is False]
        except:
            pass

    if any(a):
        if len(a) == 1:
            try:
                a = a[0]
            except:
                a= ''.join(a)

    try:
        a = [i for i in a if i!='' ]
    except:
        pass
    return a





class Superdict(dict):

    def __init__(__self, *args, **kwargs):
        object.__setattr__(__self, '__parent', kwargs.pop('__parent', None))
        object.__setattr__(__self, '__key', kwargs.pop('__key', None))
        object.__setattr__(__self, '__frozen', False)

        for arg in args:
            if not arg:
                continue
            elif isinstance(arg, dict):
                for key, val in arg.items():
                    __self[key] = __self._hook(val)
            elif isinstance(arg, tuple) and (not isinstance(arg[0], tuple)):
                __self[arg[0]] = __self._hook(arg[1])
            else:
                for key, val in iter(arg):
                    __self[key] = __self._hook(val)

        for key, val in kwargs.items():
            __self[key] = __self._hook(val)

    def __setattr__(self, name, value):
        if hasattr(self.__class__, name):
            raise AttributeError("'Superdict' object attribute "
                                 "'{0}' is read-only".format(name))
        else:
            self[name] = value

    def __setitem__(self, name, value):
        debug = False
        isFrozen = (hasattr(self, '__frozen') and
                    object.__getattribute__(self, '__frozen'))
        if isFrozen and name not in super(Superdict, self).keys():
            raise KeyError(name)

        istdictda = isinstance(value, dict)

        if istdictda is True:
            super(Superdict, self).__setitem__(name, value)
        if istdictda is False:

            try:
                base = {}
                for key33, value2 in self.items():
                    # print(key33)
                    # print(value2)
                    if key33 == name:
                        value = value2.copy() + [value]
                    if isinstance(value2, (list, tuple)):
                        try:
                            if name == base:
                                base[key33].append(value2)
                        except:
                            continue
                    else:
                        base[key33].append(value2)
            except Exception as Fehler:
                if debug is True: print(Fehler)

            try:
                if isinstance(value[-1], set):
                    value = list(value[-1])
                    if len(value) == 1:
                        value = value[0]
            except: pass
            try:
                isttupleda = isinstance(value[-1], tuple)
                if isttupleda is True:
                    try:
                        if value[-1][0] == 'FLATTEN':
                            if value[-1][1] == 'FLATTEN':
                                    value = value[:-1]
                                    value = flattenlist_neu_ohne_tuple(value)
                    except Exception as Fehler:
                        if debug is True: print(Fehler)
            except Exception as Fehler:
                if debug is True: print(Fehler)

            islistda = isinstance(value, list)

            if islistda is False:
                super(Superdict, self).__setitem__(name, [value])
            if islistda is True:

                super(Superdict, self).__setitem__(name, value)
        try:
            p = object.__getattribute__(self, '__parent')
            key = object.__getattribute__(self, '__key')
        except AttributeError:

            p = None
            key = None
        if p is not None:
            p[key] = self
            object.__delattr__(self, '__parent')
            object.__delattr__(self, '__key')

    def __add__(self, other):
        if not self.keys():
            return other
        else:
            self_type = type(self).__name__
            other_type = type(other).__name__
            msg = "unsupported operand type(s) for +: '{}' and '{}'"
            raise TypeError(msg.format(self_type, other_type))

    @classmethod
    def _hook(cls, item):
        if isinstance(item, dict):
            return cls(item)
        elif isinstance(item, (list, tuple)):
            return type(item)(cls._hook(elem) for elem in item)
        return item

    def __getattr__(self, item):
        return self.__getitem__(item)

    def __missing__(self, name):
        if object.__getattribute__(self, '__frozen'):
            raise KeyError(name)
        return self.__class__(__parent=self, __key=name)

    def __delattr__(self, name):
        del self[name]

    def to_dict(self):
        base = {}
        for key, value in self.items():
            if isinstance(value, type(self)):
                base[key] = value.to_dict()
            elif isinstance(value, (list, tuple)):
                base[key] = type(value)(
                    item.to_dict() if isinstance(item, type(self)) else
                    item for item in value)
            else:
                base[key] = value
        return base

    def copy(self):
        return copy.copy(self)

    def deepcopy(self):
        return copy.deepcopy(self)

    def __deepcopy__(self, memo):
        other = self.__class__()
        memo[id(self)] = other
        for key, value in self.items():
            other[copy.deepcopy(key, memo)] = copy.deepcopy(value, memo)
        return other

    def update(self, *args, **kwargs):
        other = {}
        if args:
            if len(args) > 1:
                raise TypeError()
            other.update(args[0])
        other.update(kwargs)
        for k, v in other.items():
            if ((k not in self) or
                    (not isinstance(self[k], dict)) or
                    (not isinstance(v, dict))):
                self[k] = v
            else:
                self[k].update(v)

    def __getnewargs__(self):
        return tuple(self.items())

    def __getstate__(self):
        return self

    def __setstate__(self, state):
        self.update(state)

    def __or__(self, other):
        if not isinstance(other, (Superdict, dict)):
            return NotImplemented
        new = Superdict(self)
        new.update(other)
        return new

    def __ror__(self, other):
        if not isinstance(other, (Superdict, dict)):
            return NotImplemented
        new = Superdict(other)
        new.update(self)
        return new

    def __ior__(self, other):
        self.update(other)
        return self

    def setdefault(self, key, default=None):
        if key in self:
            return self[key]
        else:
            self[key] = default
            return default

    def freeze(self, shouldFreeze=True):
        object.__setattr__(self, '__frozen', shouldFreeze)
        for key, val in self.items():
            if isinstance(val, Superdict):
                val.freeze(shouldFreeze)

    def unfreeze(self):
        self.freeze(False)

    def convert_to_json(self):
        json_object = json.dumps(self, indent=4)
        return json_object

    def to_normal_exec_stringdict(self):
        tag_list = []

        def print_dict___xx(v, prefix=''):
            if isinstance(v, dict):
                for k, v2 in v.items():
                    k = str(k)
                    p2 = "{}['{}']".format(prefix, k)
                    print_dict___xx(v2, p2)
            elif isinstance(v, list):
                templiste = []
                for i, v2 in enumerate(v):
                    templiste.append(v2)
                p2 = "{}".format(prefix)
                print_dict___xx(str(templiste), p2)
            else:
                zum_drucken = '{} = {}'.format(prefix, repr(v))
                tag_list.append(zum_drucken)

        print_dict___xx(self, prefix='')

        tag_list = Superdict.delete_duplicates_from_nested_list(tag_list)
        return '\n'.join(tag_list)

    @staticmethod
    def string_dict_vorbereiten(string_von_dict):
        inlines = string_von_dict.splitlines()
        inlines = [re.sub(r'^\s*\[', 'dl\g<0>', line.strip()) for line in inlines if len(line) >= 3]
        inlines = [re.sub(r'"\[', '[', line) for line in inlines]
        inlines = [re.sub(r'\]"', ']', line) for line in inlines]
        return inlines.copy()

    def dict_zur_suche_vorbereiten(self, debug=False):

        blabla = self.to_normal_exec_stringdict()
        if debug is True: print(blabla)
        gesplittet = Superdict.string_dict_vorbereiten(blabla)
        if debug is True: print(gesplittet)
        liste = []
        for ge in gesplittet:
            ge2 = regex.sub(r'^dl(\[[^\]]+\])+(?![\s=])', '', ge)
            if debug is True: print(liste)
            liste.append(ge2)
        if debug is True: print(liste)
        return liste.copy()

    @staticmethod
    def string_to_superdict(string_von_dict, debug=False):
        if isinstance(string_von_dict, list):
            string_von_dict = Superdict.delete_duplicates_from_nested_list(string_von_dict)
            string_von_dict = '\n'.join(string_von_dict)

        dl = Superdict()

        inlines = Superdict.string_dict_vorbereiten(string_von_dict)
        aktualisiert = []
        for i in inlines:
            if debug is True: print(i)
            i = regex.sub(r"'(\[\d+\])'", '\g<1>', i )
            i = regex.sub(r"\bnp\.nan\b", 'None', i )
            i = regex.sub(r"\bnan\b", 'None', i)
            i = regex.sub(r"\bNA\b", 'None', i)

            #i = regex.sub(r"\]'\]", ']', i)
            aktualisiert.append(i)
        codeausfuehren = '\n'.join(aktualisiert)
        exec(codeausfuehren)
        return dl

    @staticmethod
    def delete_duplicates_from_nested_list(nestedlist):
        """01.11"""
        tempstringlist = {}
        for ergi in nestedlist:
            tempstringlist[str(ergi)] = ergi
        endliste = [tempstringlist[key] for key in tempstringlist.keys()]
        return endliste.copy()


    def suchen_einen_wert_im_ganzen_dict(self, gesuchterendschluessel):
        return self.keys_crawler(gesuchterendschluessel=gesuchterendschluessel)

    def suchen_keys_mit_regex(self, regexsuchekeys):
        return self.keys_crawler(regexsuchekeys=regexsuchekeys)

    def suchen_werte_mit_regex(self, regexsuche):
        return self.keys_crawler(regexsuche=regexsuche)

    def get_alle_items_als_tuple(self):
        return self.keys_crawler(alle_items_zurueck=True)

    def normalize_keys(self):
        return self.keys_crawler(normalize_keys=True)

    def zaehlen_values(self):
        return self.keys_crawler(values_zaehlen=True)

    def ersetzen_einen_wert_im_dict(self, gesuchter_wert, replace):
        return self.keys_crawler(gesuchter_wert=gesuchter_wert, replace=replace)

    def ersetzen_einen_key_im_dict(self, gesuchter_key, replace):
        return self.keys_crawler(gesuchter_key=gesuchter_key, replace=replace)

    def keys_crawler(self, regexsuche=None, regexsuchekeys=None, alle_items_zurueck=False, normalize_keys=False, values_zaehlen=False,gesuchter_wert=None, gesuchter_key=None, replace=None, gesuchterendschluessel=None, debug=False ):
        beidezusammen = []
        ergebnis = []
        dl = Superdict()


        dict_zur_suche_vorbereiten = self.dict_zur_suche_vorbereiten()
        for di in dict_zur_suche_vorbereiten:
            di = 'dl' + di
            di2 = regex.sub(r'''["\[\]\(\),\{\}']''', '', di)
            di2 = regex.split(r'\s*=\s*', di2)
            beidezusammen.append([di, di2])



        if values_zaehlen is True:
            zweitesergebnisdict = Superdict()
            [print(kk) for kk in beidezusammen]
            formatierung_mit_anfuehrungszeichen = []
            for reg in beidezusammen:
                reggi = reg[0]
                if debug is True: print(reggi)
                reggi = regex.sub(r'^(dl)+', '', reggi)
                if debug is True: print(reggi)
                gesplittet = regex.split(r'\s*=\s*', reggi)
                formatierung_mit_anfuehrungszeichen.append([reg[0], gesplittet])

            indexlist = [kk[1][1] for kk in formatierung_mit_anfuehrungszeichen]
            keyliste = [kk[1][0] for kk in formatierung_mit_anfuehrungszeichen]

            if debug is True: print(indexlist)

            for i,kka in zip(indexlist,keyliste):
                dl[i] = indexlist.count(str(i))
                indexes = [ii for ii, j in enumerate(indexlist) if str(j) == str(i)]
                dl[i] = indexes, kka
            for keys,values in dl.items():
                try:
                    for valli in values:
                        if isinstance(valli, tuple):
                            if debug is True: print(f'Der Wert {keys} ist in folgenden Keys {valli}')
                            valli = str(valli[-1]).strip('''['"]''')
                            if debug is True: print(valli)
                            keys = regex.sub(r'''^['"\s]+''', '', keys)
                            keys = regex.sub(r'''['"\s]+$''', '', keys)

                            befehlausfuehren = f'zweitesergebnisdict[{values[0]}]{keys} = "{valli}"'
                            if debug is True: print(befehlausfuehren)
                            exec(befehlausfuehren)
                except Exception as Fehler:
                    if debug is True: print(Fehler)
            if debug is True: pp(zweitesergebnisdict)
            return zweitesergebnisdict

        if gesuchterendschluessel is None:
            pass
        else:
            dictstring= self.to_normal_exec_stringdict()
            for bei,didi in zip(beidezusammen, dictstring.splitlines()):
                if debug is True: print(bei)
                if debug is True: print(didi)
                keys_und_values = regex.split(r'\s*=\s*', didi)
                keys_ohne_gaensefuessle = regex.split(r'''[\'"[\]]+''',keys_und_values[0])
                keys_ohne_gaensefuessle = flattenlist_neu_ohne_tuple(keys_ohne_gaensefuessle)
                if debug is True: print(keys_ohne_gaensefuessle)
                keys_ohne_gaensefuessle = flattenlist_neu_ohne_tuple(keys_ohne_gaensefuessle)
                if debug is True: print(keys_ohne_gaensefuessle)
                for keyy in keys_ohne_gaensefuessle:
                    zwischenergebnis = regex.findall(gesuchterendschluessel, keyy)
                    zwischenergebnis  = flattenlist_neu_ohne_tuple(zwischenergebnis, nanundleerweg=True)
                    if any(zwischenergebnis):
                        t1 = regex.sub(r'''^(dl)*['"]*\[''' , '[', keys_und_values[1])
                        t1 = regex.sub(r'''\]['"]*\s*$''' , ']', t1)
                        try:
                            t1 = ast.literal_eval(t1)
                        except:
                            try:
                                t1 = regex.sub(r'''^["'\s]*''', '', t1)
                                t1 = ast.literal_eval(t1)
                            except:
                                pass
                        try:
                            if len(t1) == 1:
                                if isinstance(t1[0], (list,tuple)):
                                    pass
                                else:
                                    t1 = t1[0]
                        except:
                            pass

                        ergebnis.append([keys_ohne_gaensefuessle, t1])
            return ergebnis.copy()

        if gesuchter_wert is None and gesuchter_key is None:
            pass
        else:
            dictstring = self.to_normal_exec_stringdict()
            beidezusammen = []
            valueschecken = False
            keyschecken = False
            if gesuchter_wert is not None:
                valueschecken = True
                suchen = gesuchter_wert
                ersetzen = replace
            if gesuchter_key is not None:
                keyschecken = True
                suchen = gesuchter_key
                ersetzen = replace
            if debug is True: print(f'{gesuchter_wert} {gesuchter_key} {suchen} {ersetzen}')
            dict_zur_suche_vorbereiten = self.dict_zur_suche_vorbereiten()
            for di in dict_zur_suche_vorbereiten:
                di = 'dl' + di
                di2 = regex.sub(r'''["\[\]\(\),\{\}']''', '', di)
                di2 = regex.split(r'\s*=\s*', di2)
                beidezusammen.append([di, di2])
                if debug is True: print(beidezusammen)
            for bei in beidezusammen:
                if debug is True: print(bei[0])
                gesplittet = regex.split(r'\s*=\s*', bei[0])
                ergebnisse_klein = []
                for eni, ge in enumerate(gesplittet):
                    if eni % 2 == 0:
                        if valueschecken is True:
                            ergebnisse_klein.append(ge)
                            continue
                        if debug is True: print('Keys checken')

                    if eni % 2 != 0:
                        if keyschecken is True:
                            ergebnisse_klein.append(ge)

                            continue
                        if debug is True: print('values checken')
                    temporaer_zum_suchen = regex.sub(r'''^(?:dl)?['"]*\[['"]*''', '', ge)
                    temporaer_zum_suchen = regex.sub(r'''["'\]]+$''', '', temporaer_zum_suchen)
                    zwischenersetzen = regex.sub(suchen, ersetzen, temporaer_zum_suchen)
                    endergebnis = regex.sub(regex.escape(temporaer_zum_suchen), zwischenersetzen, ge)
                    ergebnisse_klein.append(endergebnis)

                ergebnis.append(ergebnisse_klein.copy())

            if valueschecken is True:
                for ergs, didi in zip(ergebnis, dictstring.splitlines()):
                    if debug is True: print(didi)
                    if debug is True: print(ergs)
                    originalgesplittet = regex.split(r'\s*=\s*', didi)
                    originalgesplittet_key = originalgesplittet[0]
                    try:
                        ausfuehren = f'dl{originalgesplittet_key} = {ast.literal_eval(ergs[1])}'
                        exec(ausfuehren)

                    except:
                        ausfuehren = f'dl{originalgesplittet_key} = {ergs[1]}'
                        exec(ausfuehren)
                return dl

            if keyschecken is True:
                for ergs, didi in zip(ergebnis, dictstring.splitlines()):
                    didi = f'dl{didi}'
                    ersetzen = regex.sub(r'^(dl)+', '', ergs[0])
                    neuerkey = regex.sub(r'\[[^\]]+\](?=\s+=)', ersetzen, didi)
                    neuerkey = regex.split(r'\s*=\s*', neuerkey)
                    try:
                        neuerkey = f'{neuerkey[0]} = {ast.literal_eval(neuerkey[1])}'
                    except:
                        neuerkey = f'{neuerkey[0]} = {neuerkey[1]}'

                    try:
                        exec(neuerkey)
                    except:
                        exec(neuerkey)
                return dl

        if normalize_keys is True:
            for reg in beidezusammen:
                reggi = reg[0]
                reggi = regex.sub('^dl', '', reggi)
                gesplittet = regex.split(r'\s*=\s*', reggi)
                keys = gesplittet[0]
                keys = regex.sub(r"'\]\['", 'ÇYÇYÇ', keys)
                keys = regex.sub(r"'\](\[\d+\])?", 'ÇAÇAÇ', keys)
                keys = regex.sub(r"^\s*\['", 'ÇEÇEÇ', keys)
                keys = regex.sub(r'\W+', '_', keys)
                keys = regex.sub(r'_+Ç', 'Ç', keys)
                keys = regex.sub(r'Ç_+', 'Ç', keys)
                keys = regex.sub(r'Ç(\d+)', 'Çz_\g<1>', keys)
                keys = regex.sub('ÇYÇYÇ', "']['", keys)
                keys = regex.sub('ÇEÇEÇ', "dl['", keys)
                keys = regex.sub('ÇAÇAÇ', "']", keys)
                keys = keys.lower()
                keys = keys.strip(' _')
                try:
                    ergebnis.append(f'{keys} = {ast.literal_eval(gesplittet[1])}')
                except:
                    ergebnis.append(f'{keys} = {gesplittet[1]}')
            for eni, ergi in enumerate(ergebnis):
                if debug is True: print(ergi)
                exec(ergi)
            return dl

        if alle_items_zurueck is True:
            for reg in beidezusammen:
                valueformatieren = regex.sub(r'^[^=]+=\s*', '', reg[0])
                keyformatieren = regex.sub('^dl','',reg[1][0])

                try:
                    hinzufuegen = keyformatieren, ast.literal_eval(valueformatieren)
                except:
                    hinzufuegen = keyformatieren, valueformatieren
                ergebnis.append(hinzufuegen)
            return ergebnis.copy()

        if regexsuche is not None:
            for reg in beidezusammen:
                ergi = regex.findall(regexsuche, reg[1][1])
                ergi = flattenlist_neu_ohne_tuple(ergi)
                if any(ergi):
                    ergebnis.append(reg[0])
            for eni, ergi in enumerate(ergebnis):
                exec(ergi)
            return dl

        if regexsuchekeys is not None:
            for reg in beidezusammen:
                ergi = regex.findall(regexsuchekeys, reg[1][0])
                ergi = flattenlist_neu_ohne_tuple(ergi)
                if any(ergi):
                    ergebnis.append(reg[0])
            for eni, ergi in enumerate(ergebnis):
                exec(ergi)
            return dl

einfuehrung.py

from maximize_console import *
from farbprinter.farbprinter import Farbprinter
drucker = Farbprinter()
from add_color_print import add_color_print_to_regedit, updates_quero_estudar_alemao
def einfuehrung(name):
    print(1000 * "\n")
    maximize_console(lines=30000)
    add_color_print_to_regedit()
    colorfunctionslogo = [drucker.f.black.red.normal, drucker.f.black.brightyellow.normal]
    drucker.p_ascii_front_on_flag_with_border(
        text=name,
        colorfunctions=colorfunctionslogo,
        bordercolorfunction=drucker.f.brightgreen.black.italic,
        font="slant",
        width=1000,
        offset_from_left_side=5,
        offset_from_text=15,
    )
    colorfunctionspage = [
        drucker.f.black.brightwhite.normal,
        drucker.f.black.brightgreen.normal,
    ]
    drucker.p_ascii_front_on_flag_with_border(
        text="www . queroestudaralemao . com . br",
        colorfunctions=colorfunctionspage,
        bordercolorfunction=drucker.f.brightgreen.black.negative,
        font="slant",
        width=1000,
        offset_from_left_side=1,
        offset_from_text=1,
    )
    updates_quero_estudar_alemao()

Artigos relacionados

Respostas

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Start a Conversation

Hi! Click one of our member below to chat on Whatsapp

Suporte técnico

Suporte técnico

Suporte técnico - mande uma mensagem!

online

Depois de muitos problemas de saúde, finalmente, estou de volta!

Há novas vagas nos cursos on-line