def solver(inlist): """ Generate all solutions to the word rummy board. Col4 is a list of sorted letter values for each column. Col3 is a list of 4 item lists, where each entry is a possible 3 letter combination in a column. Loop through all 3 and 4 letter runs, and see how the fit on the front and on the back of each word combination. """ NROWS = 4 MINRUNL = 3 MAXRUNL = 4 wlist = WordList() ncol = len(inlist)/NROWS board = [] inpt = iter(inlist) for row in range(0, NROWS): board.append([]) for col in range(0, ncol): board[row].append(inpt.next()) col4 = [] col3 = [] for col in range(0, ncol): cval = [] for row in range(0, NROWS): cval.append(board[row][col]) cstr = ''.join(sorted(cval)) col4.append(cstr) tarr3 = [] tarr3.append(''.join(cstr[0:3])) tarr3.append(''.join([cstr[0],cstr[2:]])) tarr3.append(''.join([cstr[0:2],cstr[3]])) tarr3.append(''.join(cstr[1:])) col3.append(tarr3) lines = [] for row in range(0, NROWS): lines.append(''.join(board[row])) ans_dict = {} for row in range(0, NROWS): for indx in range(0, ncol - MINRUNL + 1): for rlen in [MINRUNL, MAXRUNL]: if rlen + indx > ncol: continue runv = lines[row][indx:indx + rlen] tailv = wlist.findStart(runv) headv = wlist.findEnd(runv) for entry in tailv: mval = find_sol(entry, runv, col3, col4, indx) if mval >= 0: score_it(ans_dict, [0, entry, runv, indx, mval]) for entry in headv: mval = find_sol(entry, runv, col3, col4, indx) if mval >= 0: score_it(ans_dict, [1, entry, runv, indx, mval]) olist = [] for entry in ans_dict: olist.append([entry, ans_dict[entry], ptval(ans_dict[entry])]) return gen_html(olist);
def unionResultSets(sets): """ perform intersection of ResultSets """ docids = DocidList() words = WordList() for set in sets: docids = union(docids, set.docids) words.extend(set.words) return ResultSet(docids, words)
def _puffery(segmentsAdded): wordList = WordList() wordList.parse("pufferyOutput.txt") segmentsAdded = mwp.parse(segmentsAdded) retScore = 0.0; for key in wordList: count = segmentsAdded.count(key) count += segmentsAdded.count(key.title()) if count > 0: retScore += count * wordList[key] return retScore
def load_word_list(self, word_list_name: str): """ 保存当前清单,切换到新的清单 :param word_list_name: :return: """ if self.word_list is not None: self.word_list.write_list('../wordlist/' + self.word_list.name + '.wl') self.word_list = WordList(word_list_name, '../wordlist/' + word_list_name + '.wl')
def intersectionResultSets(sets): """ perform intersection of ResultSets """ if not sets: return ResultSet(DocidList(), WordList()) docids = sets[0].getDocids() words = WordList(sets[0].getWords()) for set in sets[1:]: docids = intersection(docids, set.docids) words.extend(set.words) return ResultSet(docids, words)
def RemoveWord(): doContinue = True myMenu = Menu() API = WordList() while doContinue: os.system("cls") myMenu.ShowTitle("Remove word") wordToSearch = myMenu.RequestWord() myMenu.SearchMenu() os.system("cls") API.RemoveWord(wordToSearch) continueResp = myMenu.Continue("remove another word") if continueResp == "n" or continueResp == "N": doContinue = False
def AddWord(): doContinue = True myMenu = Menu() API = WordList() while doContinue: os.system("cls") myMenu.ShowTitle("Add a new word") wordToSearch = myMenu.RequestWord() myMenu.SearchMenu() os.system("cls") API.AddNewWord(wordToSearch) continueResp = myMenu.Continue("add another word") if continueResp == "n" or continueResp == "N": doContinue = False
def GetExample(): doContinue = True myMenu = Menu() API = WordList() while doContinue: os.system("cls") myMenu.ShowTitle("Get Example") wordToSearch = myMenu.RequestWord() myMenu.SearchMenu() os.system("cls") API.GetExample(wordToSearch) continueResp = myMenu.Continue("search another example") if continueResp == "n" or continueResp == "N": doContinue = False
def on_pre_enter(self): self.header.text = self.title self.wordlist = WordList(self.title, self.language) AddWindow.wordlist = self.wordlist AddWindow.language = self.language DeleteWindow.wordlist = self.wordlist QuizWindow.wordlist = self.wordlist
def choose_wordlist(): os.system('clear') print("What wordlist do you want to use? Choose one:") existing = os.listdir( '/Users/willeeriksson/Documents/Programmering/learnspanish/wordlists/') list_existing(existing) choice = int(input()) name = parse_choice(choice, existing) wl = WordList(name) return wl
def load_wordlist(self, name, fname): wordlist_fname = os.path.join(self.book_dir, fname) dump_fname = os.path.join(self.dump_dir, fname + DUMP_SUFFIX) if os.path.exists(dump_fname) and not_modified(wordlist_fname, dump_fname): # load from cache with open(dump_fname, 'rb') as pickle_file: wordlist = pickle.load(pickle_file) else: # load from original file and dump if os.path.exists(dump_fname): logging.info( "[parsing] File modification detected, re-parse '%s'" % wordlist_fname) else: logging.info("[parsing] '%s'" % wordlist_fname) wordlist = WordList(name, wordlist_fname) dump_path = os.path.dirname(dump_fname) if not os.path.exists(dump_path): os.makedirs(dump_path) with open(dump_fname, 'wb') as pickle_file: pickle.dump(wordlist, pickle_file) logging.info("[loaded] WordList '%s'" % name) return wordlist
import random import string import operator from collections import Counter import colorama import text_color from wordlist import WordList hard_mode = True # deducts double points for incorrect vowels when enabled. colorama.init() vowels = frozenset({'A', 'E', 'I', 'O', 'U'}) word_list = WordList('states') mystery_word = word_list.mystery_word mystery_len = len(mystery_word) mystery_list = list(mystery_word) mystery_vowels = list(vowels.intersection(mystery_word)) remaining_vowels = random.sample(mystery_vowels, len(mystery_vowels)) found_list = list('_' * mystery_len) guess_log = list() status_log = list() score_log = list() found = 0 prompt = 'Guess a letter, or guess the word.' # initial prompt if ' ' in mystery_list: for index, letter in enumerate(mystery_list): if letter == ' ':
class AddWindow(Screen): """ Window with an interface for adding words as well as displaying their translations. """ wordlist = WordList("aaaa", "spanish") # wordlist = None language = "spanish" input = ObjectProperty(None) word = ObjectProperty(None) translation = ObjectProperty(None) other_translations = ObjectProperty(None) def on_pre_enter(self): """Resets graphics of AddWindow every time it is entered.""" self.ids.input.text = "" self.ids.word.text = "" self.ids.translation.text = "" self.ids.other_translations.text = "" def add(self): """Adds text in TextInput as a new word to the wordlist.""" new_word = self.input.text error_occured = False error_message = "" if new_word == "": return try: translations = get_translations(new_word, self.language) except Exception as e: error_occured = True error_message = str(e) if error_occured: self.display_error_message(error_message) elif translations == None: self.not_in_dictionary(new_word) else: self.wordlist.add_word(new_word, translations) self.display_translations(new_word, translations) self.reset() def display_error_message(self, message): self.ids.translation.text = message def not_in_dictionary(self, new_word): self.ids.translation.text = "The word '%s' does not seem to be in the dictionary" % new_word.capitalize( ) def display_translations(self, new_word, translations): """Updates the graphics shown on the screen, displaying the word, its primary translation as well as other translations if available.""" self.ids.word.text = new_word.capitalize() translations = [t.capitalize() for t in translations] self.ids.translation.text = "Translation: " + translations[0] if len(translations) > 1: self.ids.other_translations.text = "Other translations: " + ", ".join( translations[1:]) def reset(self): """Resets the text in TextInput, making it blank.""" self.input.text = ""
class Vacalbulary: def __init__(self): # 应该每次从文件中读取单词清单,而不是一股脑存在内存里,只同时存一个 # 测试 self.word_list_names: List[str] = [] self.load_word_list_name() self.word_list: WordList = None self.word_pool: WordPool = WordPool('all_word.json') def load_word_list_name(self): """ 载入已经存在的清单的名字 :return: """ self.word_list_names.clear() for maindir, subdir, all_file in os.walk('../wordlist'): for filename in all_file: apath = os.path.join(maindir, filename) # *.wl 表示清单文件 if apath.endswith('.wl'): self.word_list_names.append(apath) def creat_new_list(self, word_list_name: str) -> bool: """ 新建清单并创建配套的文件 :param word_list_name: :return: 是否创建成功 """ if word_list_name in self.word_list_names: return False self.word_list_names.append(word_list_name) f = open('../wordlist/' + word_list_name + '.wl', "w", encoding="utf-8") f.write('{}') f.close() return True def load_word_list(self, word_list_name: str): """ 保存当前清单,切换到新的清单 :param word_list_name: :return: """ if self.word_list is not None: self.word_list.write_list('../wordlist/' + self.word_list.name + '.wl') self.word_list = WordList(word_list_name, '../wordlist/' + word_list_name + '.wl') def save_current_list(self): """ 保存当前的清单 """ self.word_list.write_list('../wordlist/' + self.word_list.name + '.wl') def save_dict(self): """ 保存当前词库 """ self.word_pool.write2file('all_word.json') def get_front_word(self) -> Word: """ 获取最小熟练度的单词 :return: """ return self.word_list.get_min_proficiency_word(self.word_pool) def change_proficiency(self, english_meaning: str, _choice: str): """ 修改单词熟练度 :param english_meaning: :param _choice: :return: """ self.word_list.change_word_proficiency(english_meaning, _choice, self.word_pool) def add_word(self, english_meaning: str): assert self.word_list is not None if not self.word_pool.has(english_meaning): return self.word_list.add_word(english_meaning) def remove_word(self, english_meaning: str): assert self.word_list is not None if not self.word_pool.has(english_meaning): return self.word_list.remove_word(english_meaning)
def interface(): MW = MainWindow() wl = WordList(MW.main()) return choose_action(wl)
from wordlist import WordList myclass = WordList() myclass.AddNewWord("Chunk")
def main(): file = WordList('wordsEn.txt') a = Anagramizer('more money', file) anagrams = a.generateAnagrams() print(anagrams)
from transformations import vowel_expand, drop_vowel, l33t, words_with_ck, repeat_to_single, drop_suffixes from wordlist import WordList import itertools import os import re ALPHABET = '23456789abcdefghijkmnpqrstuvwxyz' assert len(list(itertools.product(ALPHABET, repeat=5))) == 33554432 wordlist = WordList(lower=True, strip_nonalpha=True) def not_in_alphabet(word, alphabet=ALPHABET): if re.findall('[^{}]'.format(alphabet), word): return True return False # https://github.com/shutterstock/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words # https://github.com/shutterstock/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words/archive/master.zip # http://www.noswearing.com/dictionary # http://wiki.spiralknights.com/List_of_known_filtered_words for filename in ['de', 'en', 'es', 'fr', 'it', 'nl', 'pt', 'ru', 'custom.txt', 'noswearing.txt', 'sega.txt']: # 'ja', 'zh' fn = os.path.join('dictionaries/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words-master', filename) wordlist.add_file(fn, min=3, max=15, reject=[not_in_alphabet], transforms=[ lambda x: vowel_expand(x, 5) if len(x) < 5 else [], lambda x: drop_vowel(x), lambda x: l33t(x) if 3 <= len(x) <= 5 else [], lambda x: words_with_ck(x), lambda x: repeat_to_single(x), lambda x: drop_suffixes(x)
from wordlist import WordList from phraselist import PhraseList from w2w_feature import W2WFeature wordList = WordList() wordList.parse("pufferyOutput.txt") w2wFeature = W2WFeature(wordList) print("output below should be 1, 2, 0") print(w2wFeature.generateFeatureValue(["joe", "is", "legendary"])) print( w2wFeature.generateFeatureValue(["joe", "is", "legendary", "and", "adept"])) print(w2wFeature.generateFeatureValue(["joe", "is", "cat", "dog", "dolphin"])) phraseList = PhraseList() phraseList.parse("phrase.csv") w2wFeature = W2WFeature(phraseList) print("ouput below should be 1, 1, 2, 0") print(w2wFeature.generateFeatureValue(["the", "dog", "sleep"])) #should print 1 print( w2wFeature.generateFeatureValue(["the", "dog", "sleep", "happy", "dreams"])) #should print 1 print( w2wFeature.generateFeatureValue( ["the", "dog", "sleep", "happy", "dreams", "the", "dog", "sleep"])) #should print 0 print(w2wFeature.generateFeatureValue(["the", "dog", "not", "sleep"])) #should print 0
def main(): wordList = WordList().get_random_words() wordSearch = WordSearch().get_json(wordList) print(wordSearch)