Esempio n. 1
0
def search():
    with open("words.json", 'r') as f:
        words = json.load(f)
        f.close()

    with open("Not Remember", 'r') as f:
        nrList = f.read().strip().split("\n")
        f.close()

    print("Words Available\n-------------------------------\n")
    wordList = list(words.keys())
    j = 0
    for i in wordList:
        if j < 10:
            if i.upper() in nrList:
                color = 'red'
            else:
                color = 'cyan'

            print(colored(i.capitalize(), color), end=', ')
            j += 1
        else:
            print("\n")
            j = 0
    print(f"{len(wordList)} words in total")
    print("\n")

    while True:
        word = input("Search word: ").upper()
        if word.upper() == 'N':
            return
        if word in words.keys():
            print("Heres the meaning: ")
            print("\n=============================\n")
            print(colored(word, 'green'))
            parse_dict(len(word), None, words[word])
            print("\n=============================\n")

        else:
            print(
                f"{colored('We dont have this word, !!! sorry', 'red')} \N{disappointed face}"
            )

        if input("Would you like to search more ?(Y/N)").upper() == 'N':
            break

    return
Esempio n. 2
0
def count(file):
    pairs = parse_dict(file)
    counter = 0
    print(len(pairs))
    for i in range(len(pairs)):
        t = pairs[i][1]
        counter += len(t) * (len(t)-1)
    return counter
Esempio n. 3
0
def read():
    words = dict()
    with open("words.json", 'r') as f:
        words = json.load(f)
        f.close()

    print(f"You have {len(words.keys())} unique words")

    try:
        nr = open("Not Remember", 'r')
        nrList = nr.read().strip().split("\n")
        print(f"{'*'*40}")
        print(f"{' '*10}{colored('Priority Words'.upper(), 'yellow')}\n")
        j = 0
        for i in nrList:
            if j <= 5:
                j += 1
                print(f"{colored(i, 'cyan')}", end=" " * 2)
            else:
                j = 0
                print()
        print(f"\n{'*'*40}\n")
    except:
        pass

    input()

    for key in words.keys():
        print("=========================================\n")

        print(colored(key, 'green'))
        parse_dict(len(key.strip()), None, words[key])

        print("\n=========================================")
        waitKey = input()
        if waitKey == '':
            continue
        else:
            return

    print(colored("All Words Finished", 'yellow'))
Esempio n. 4
0
def get_distant(model, direct, filepath, form='csv', find_n=False, ps=0):
    #for excel files
    #doing workbooks
    tmp_tag = {
        1: '_NOUN',
        2: '_VERB',
        3: '_ADJ',
        4 :'_ADV'
    }
    unknown_words = { i:0 for i in range(1, 5)}

    tmp = [xlwt.Workbook() for i in range(5)]
    files = [tmp[i].add_sheet('Word_{:d}'.format(i)) for i in range(5)]
    curr = [0 for i in range(5)]
    parsed = parse_dict(filepath, kind='word')
    os.makedirs(direct)

    #cycle for pairs of words
    for i in range(len(parsed)):
        t = parsed[i]
        pairs = t[1]
        cl = 0
        if ps and t[0] != ps:
            continue
        for j in range(len(pairs)):
            for p in range(j+1, len(pairs)):
                k = api_similarity(model, pairs[j] + tmp_tag[t[0]], pairs[p]+tmp_tag[t[0]])
                if 'nknown'not in k:
                    k = float(k)
                    if find_n:
                        z = search_word(model,pairs[j] + tmp_tag[t[0]], pairs[p] + tmp_tag[t[0]], form)
                        other_z = search_word(model,pairs[p] + tmp_tag[t[0]], pairs[j] + tmp_tag[t[0]], form) 
                        #z = search_word(model,pairs[j] + tmp_tag[t[0]], pairs[p], form)
                        #other_z = search_word(model,pairs[p] + tmp_tag[t[0]], pairs[j], form)

                    files[t[0]-1].write(curr[t[0]-1], 0, pairs[j])
                    files[t[0]-1].write(curr[t[0]-1], 1, pairs[p])
                    files[t[0]-1].write(curr[t[0]-1], 2, k)
                    if find_n and z == 'Yes' and other_z == 'Yes':
                        files[t[0]-1].write(curr[t[0]-1], 3, z)
                    cl += 1
                    curr[t[0]-1] += 1
                else:
                    unknown_words[t[0]] += 1
                    files[4].write(curr[4], 0, pairs[j])
                    files[4].write(curr[4], 1, pairs[p])
                    curr[4] += 1

    print("Total number of pairs: ", cl)
    for p in range(5):
        tmp[p].save(os.path.join(direct, 'results_{:d}.xls'.format(p)))

    print(model, unknown_words)
Esempio n. 5
0
File: mod.py Progetto: biern/bomber
 def load_config(self):
     path = os.path.join(self.dir(), self.config_filename)
     configParser = ConfigParser()
     configParser.read(path)
     if not os.path.exists(path):
         self.log.warning("Warning, mod config file not found (%s), using default settings" % path)
     # Parsing all data strings
     self.config = copy(self.default_config)
     self.config.update(config_to_dict(configParser))
     for section in self.config.keys():
         self.config[section] = parse_dict(self.config[section],
                                           self.config_parser.get(section, {}),
                                           self.log)
     
     self.log.debug("Configuration loaded")
Esempio n. 6
0
 def __init__(self, param, symmetrize=False, improving_path=[], **args):
     self.current_plot = 0
     if isinstance(param, dict):
         players = get_unique_keys(param)
         self.network = parse_dict(param)
     elif isinstance(param, int):
         players = list(range(0, param))
         self.network = {i: [] for i in [*range(0, param)]}
     else:
         self.network = {}
     if symmetrize:
         self.symmetrize()
     self.players_amount = len(players)
     # decoder is used for output. inner indexes are always integer but
     # since we may want to store actual string names for players
     # we can decode indexes into strings (and back if we really want to)
     self.decoder = lambda x: players[x]
     self.improving_path = deepcopy(improving_path)
     self.rule = args.get('rule', lambda x: 0)
Esempio n. 7
0
def practice():
    try:
        nr = open("Not Remember", 'r')
        nrList = nr.read().strip().split("\n")
        nr.close()
    except:
        nr = open("Not Remember", "w+")
        nrList = list()
        nr.close()

    with open("words.json", "r") as f:
        words = json.load(f)
        f.close()

    wordsList = list(words.keys())
    meaning_dict = meanings(words)
    while True:
        nq = int(input("How many questions would you like to do?: "))
        print(
            "In addition to this you will encounter questions you did wrong earlier."
        )
        print(f"Total number of questions: {nq + len(nrList)}\n")
        print("-" * 41, end="\n\n")
        question_id = get_questions(nq, len(wordsList))
        questions = []
        for i in question_id:
            questions.append(wordsList[i])

        for i in nrList:
            if i not in wordsList:
                nrList.remove(i)
            elif i not in questions:
                questions.append(i)

        random.shuffle(questions)

        correctAnswers = 0
        wrongQuestions = []
        for i, question in enumerate(questions):
            print("\n=============================\n")

            print(
                f"Q{i+1}/{len(questions)}. What is the meaning of {colored(question, 'blue')}"
            )
            choices, realAnswerIndex = make_choices(meaning_dict, question)
            for j, val in enumerate(choices):
                print(f"{colored(str(j+1), 'cyan')}.{val}")

            print("\nEnter choice number: ", end='')
            answer = int(input())

            if answer == realAnswerIndex + 1:
                print(f"{colored('Bingo!!!', 'green')}\N{grinning face}")
                if question in nrList:
                    nrList.remove(question)
                correctAnswers += 1

            else:
                print(f"{colored('Wrong Answer', 'red')}\N{disappointed face}")
                print(
                    f"Correct answer is {colored(choices[realAnswerIndex], 'green')}"
                )
                wrongQuestions.append(question)
                if question not in nrList:
                    nrList.append(question)

            print(f"Other meanings of {colored(question, 'green')} are")
            parse_dict(0, None, words[question]["meaning"])

            print("\n=============================\n")
            time.sleep(3)

        print(
            f"======================== {colored('Report', 'blue') }====================="
        )
        print(
            f"""Number of correct questions: {correctAnswers}\nAccuracy: {(correctAnswers/len(questions))*100}%"""
        )
        print(f"You got {len(wrongQuestions)} words wrong")
        for wq in wrongQuestions:
            print("\n=========================\n")
            print(colored(wq, 'green'))
            parse_dict(len(wq), None, words[wq]["meaning"])
            print("\n=========================\n")

        if input("Practice More (Y/N)?: ").upper() == 'N':
            nr = open("Not Remember", "w+")
            for i in nrList:
                nr.write(i)
                nr.write("\n")
            nr.close()
            break

    return
Esempio n. 8
0
def write(verbose = 'N', test = True):
    words = dict()
    sys.stdout = open(os.devnull, 'w')
    dictionary = PyDictionary('features="html.parser"')
    sys.stdout = sys.__stdout__
    cont = 'y'
    try:
        with open("words.json", "r+") as f:
            try: 
                prev_words = json.load(f)
            except:
                prev_words = dict()
            
            while cont[0].upper() != 'N':
                if cont == 'y':
                    wordList = input("Enter the word (if >1 space separated): ").split()
                else:
                    wordList = cont
                wordList = [i.upper() for i in wordList]

                for word in wordList:
                    if word in prev_words.keys():
                        print(f"\nYou have encountered the word {word}")
                        print(f"{colored('Try and remember', 'red')}\n")
                        
                        r = False
                        if test == False:
                            wait = 'y'
                            while wait.upper()=='Y':
                                time.sleep(10)
                                if input("Remember ?: ").upper() == 'Y':
                                    wait = 'n'
                                    r = True
                                if input("Cannot remember ? Want to look at the meaning ?(Y/N): ").upper() == 'Y':
                                    r = False
                                    break
                        
                        if not r:
                            nr = open("Not Remember", "r+")
                            nrList = nr.read().strip().split("\n")
                            if word not in nrList:
                                nr.write(word.upper())
                                nr.write("\n")
                            nr.close()
                            del nr
                            del nrList
                            
                            if test:
                                print(f"{colored('Bad luck look it up later', 'cyan')} \N{disappointed face}")
                            else:
                                print("Heres the meaning: ")
                                print("\n=============================\n")
                                print(colored(word, 'green'))
                                parse_dict(len(word), None, prev_words[word])
                                print("\n=============================\n")

                    else:

                        sys.stdout = open(os.devnull, 'w')
                        meaning = dictionary.meaning(word)
                        synonyms = dictionary.synonym(word)
                        antonyms = dictionary.antonym(word)
                        sys.stdout = sys.__stdout__

                        if meaning is None:
                            print(f"{colored(f'We dont have the word {word}, !!! sorry', 'red')} \N{disappointed face}")
                            nf = open("Not Found", 'a+')
                            nfList = set(nf.read().strip().split("\n"))
                            if word not in nfList:
                                nf.write(word.upper())
                                nf.write("\n")
                            nf.close()
                            del nf
                            del nfList

                        else:
                            words[word] = dict()
                            words[word]["meaning"] = meaning
                            words[word]["synonym"] = synonyms
                            words[word]["antonyms"] = antonyms

                            if verbose == 'Y':
                                print("Heres the meaning: ")
                                print("\n=============================\n")
                                print(colored(word, 'green'))
                                parse_dict(len(word), None, words[word])
                                print("\n=============================\n")
                            else:
                                print(f"{colored(f'We found the word {word}', 'green')} \N{grinning face}")

                cont = input("New word (if >1 space separated): ").split()
            
            prev_words.update(words)
            f.seek(0)
            
            try:
                json.dump(prev_words, f,indent=2, sort_keys=True)
                f.close()
            except:
                print("could not write to file")
                prev_words = json.dumps(prev_words, indent=2)
                print("Printing on console copy to the file")
                print("\n\n=========================================\n")
                print(prev_words)
                print("=========================================\n")
                f.close()

        
    except EnvironmentError as e:
        print(f"Something went wrong\n {e}")

    return