def get_other(obj, objects): """Return another object in the Iterable besides the given one.""" if len(objects) < 2: return obj # make sure there *is* another object we can choose other = rchoice(objects) while other == obj: other = rchoice(objects) return other
def __init__(self, state=None, height=4, width=4, obstacle_chance=.3): self.time_step = 0 self.resources = {} if state: # prefab level self.state = np.array(state) self.height, self.width = self.state.shape # Place the agent and the goal self.goal_pos = np.argwhere(self.state == self.input_chars['goal'])[0] self.agent_pos = np.argwhere(self.state == self.input_chars['agent'])[0] for pos in (self.agent_pos, self.goal_pos): self.state[tuple(pos)] = self.chars['empty'] else: # initialize a random VaseWorld self.height, self.width = height, width if not 0 <= obstacle_chance <= 1: raise Exception('Chance of a square containing an obstacle must be in [0, 1].') self.obstacle_chance = obstacle_chance # how likely any given square is to contain an obstacle self.state = np.random.choice([self.chars['empty'], *self.obstacles], size=(height, width), p=[1 - self.obstacle_chance, *[obstacle_chance / len(self.obstacles) for _ in self.obstacles]]) # Place the agent and the goal empty = np.argwhere(self.state == self.chars['empty']) self.agent_pos = rchoice(empty) self.goal_pos = rchoice(empty) self.original_agent_pos = self.agent_pos.copy() self.original_state = self.state.copy() self.num_squares = self.width * self.height self.clearable = self.check_clearable()
def tournament_selection(self, k=0.75): pOne, pTwo = rchoice(self.population), rchoice(self.population) # modified to avoid using __cmp__ method of chromosome if urand() < k: return pOne if pOne > pTwo else pTwo else: return pOne if pOne < pTwo else pTwo
def generateImg(data, pos1, pos2): background = Image.open("bg.png") background.convert('RGBA') bg = Image.new("RGBA", background.size, (255,255,255,255)) bg.paste(background, (0, 0)) def drawRoundPic(im, xy): im.convert('RGBA') mask = Image.open('mask.png').convert('L') nim = ImageOps.fit(im, mask.size, centering=(0.5, 0.5)) nim.putalpha(mask) bg.paste(nim, xy, nim) def drawCenterText(msg, xy, wh=(300,50)): draw.textsize(msg, font=font2) fsize = font2.getsize( msg ) draw.text(((wh[0] - fsize[0])/2 + xy[0],(wh[1]-fsize[1])/2 + xy[1]), msg, font=font2, fill="black") im = Image.open("images/"+str(pos1+1)+".jpg") drawRoundPic(im, (89, 171)) im = Image.open("images/"+str(pos2+1)+".jpg") drawRoundPic(im, (609, 171)) draw = ImageDraw.Draw( bg ) deepBlue = (0,62,142) wordCho1=rchoice(words) wordCho2=rchoice(words2) draw.text( (430, 282), wordCho1, font=font, fill=deepBlue ) draw.text( (928, 282), wordCho2, font=font, fill=deepBlue ) drawCenterText(data[pos1]['name'], (85,480)) drawCenterText(data[pos2]['name'], (608,480)) return bg
def fill_random_cell(self): empty_cells = self.get_empty_cells() if len(empty_cells) > 0: (row_index, col_index)= rchoice(empty_cells) cell_value = rchoice(self.new_cell_distribution) self.board[row_index][col_index] = cell_value return (row_index, col_index)
def run(url, depth, i): global BASE_URL global DONE global COLORMAP global currColorNum if i > depth: print(clr.Style.BRIGHT + clr.Back.WHITE + clr.Fore.BLACK + "You rode the wiki!" + clr.Style.RESET_ALL) else: DONE.append(url) POSSIBLE_URLS = list() HTML = bs(req.get(url).content, 'lxml') PAGE_TITLE = HTML.find('h1', id="firstHeading").text nextColor = COLORMAP[currColorNum] currColorNum = (currColorNum + 1) % 6 print(clr.Style.BRIGHT + clr.Fore.WHITE + ("-" * (i + 1)) + PAGE_TITLE + " - " + nextColor + url + clr.Style.RESET_ALL) for a in HTML.find_all('a', href=HREFREGEX): if a.text and validUrl(a['href']) and a['href'] not in url: for doneURL in DONE: if a['href'] not in doneURL and DONE != list(): POSSIBLE_URLS.append(a['href']) if POSSIBLE_URLS == list(): run("", depth, depth) else: SEC_URL = rchoice(POSSIBLE_URLS) while SEC_URL == url: SEC_URL = rchoice(POSSIBLE_URLS) URL = BASE_URL + SEC_URL run(URL, depth, i + 1)
def pareto_tournament_selection(self, k=0.75): '''Psuedo-Pareto tournament selection for multi-objective offspring. Offspring that are better in a majority (2/3) of the fitness terms win the tournaments.''' pOne, pTwo = rchoice(self.population), rchoice(self.population) f1 = MATH.array([pOne.fitness,pOne.parsimony,pOne.finitewts]) f2 = MATH.array([pTwo.fitness,pTwo.parsimony,pTwo.finitewts]) if urand() < k: return pOne if MATH.sign((f1-f2)).sum() > 0 else pTwo else: return pOne if MATH.sign((f1-f2)).sum() < 0 else pTwo
def _set_destination(self): """Randomly choose next url to travel""" if not self.possible_urls: self.depth_counter = self.depth else: next_url_tail = rchoice(self.possible_urls) while next_url_tail in self.next_url: next_url_tail = rchoice(self.possible_urls) self.depth_counter += 1 self.next_url = self.base_url + next_url_tail
def id_gen(length, base=BASE[16]): # """You can add a function description here to be accessed by help()""" # (remove the #) # if it is a simple problem, you can probably do it in a short list comprehension # it is even more readable (sometimes): # key is a string made of random choices from a base repeated length times key = ''.join([rchoice(base) for i in range(length)]) # numpy.random counterpart for this method: # ''.join(numpy.random.choice(list(base), length)) # if you decide to use numpy you can avoid creating the lists here # by defining the base as a list before the calling the function # (i.e. in the environment variables) # (useful if you have to repeat this many times over) # the method you had before is a bit inhumane: # key is a string made of a random selections between zero and # the length of elements from a base repeated length times # key = ''.join([base[random.randint(0, length(base))] for i in range(length)]) return key
def get_choice_egreedy(explore, num_choices, models, features): #e-greedy if random.random() < explore: return rchoice(range(num_choices)) else: probs = [model.probs_single(features)[1] for model in models] return np.argmax(probs)
async def stats(self, ctx): """A few stats.""" # get_owner = bot.get_user_info(config['ownerid']) statInfo = await ctx.bot.application_info() statEmbed = discord.Embed( title='Stats', description='This bot is' ' powered by [lolbot](https://github.com/tilda/lolbot), a fast and powerful ' 'Python bot.', colour=0x690E8) statEmbed.add_field(name='Owner', value=statInfo.owner.mention + '(' + str(statInfo.owner) + ' - ID: ' + str(statInfo.owner.id) + ')') statEmbed.add_field(name='Python', value=sys.version) statEmbed.add_field(name='discord.py', value=discord.__version__) statEmbed.add_field(name='Servers', value=len(self.bot.guilds)) statPool = [ 'What have you done now?', 'Why should I do this again?', 'Oh..', 'Where did the RAM go?', 'grumble grumble', 'Please hold.', 'No, just, no.', 'Have you tried rebooting?', 'memework makes the dreamwork!' ] statEmbed.set_footer(text=rchoice(statPool)) try: await ctx.send(embed=statEmbed) except: await ctx.send('Sorry, I can\'t send the Embed.') await ctx.send('Maybe I don\'t have Embed Links permission?') else: pass
async def stats(self, ctx): """A few stats.""" statInfo = await ctx.bot.application_info() statEmbed = discord.Embed( title='Stats', description='This bot is' ' powered by [lolbot](https://github.com/tilda/lolbot), a fast and powerful ' 'Python bot.', colour=0x690E8) statEmbed.add_field(name='Owner', value=statInfo.owner.mention + '(' + str(statInfo.owner) + ' - ID: ' + str(statInfo.owner.id) + ')') statEmbed.add_field(name='Python', value=get_python_version()) statEmbed.add_field(name='discord.py', value=discord.__version__) statEmbed.add_field(name='Servers', value=f'{len(self.bot.guilds)}') statEmbed.add_field(name='Uptime', value=bot_uptime(self.bot.init_time)) statPool = [ 'What have you done now?', 'Why should I do this again?', 'Oh..', 'Where did the RAM go?', 'grumble grumble', 'Please hold.', 'No, just, no.', 'Have you tried rebooting?', 'memework makes the dreamwork!', 'cool and good' ] statEmbed.set_footer(text=rchoice(statPool)) await ctx.send(embed=statEmbed)
def rcontract_min_cut(self): """ David Karger's '90s Random Contraction Algorithm - While there are more than 2 vertices: i. Pick a remaining edge (u,v) uniformly at random. ii. Merge (or “contract”) u and v into a single vertex. iii. Remove self-loops - Return cut represented by final 2 vertices. """ min_cut = 0 tmp_graph = deepcopy(self) total_of_nodes = len(tmp_graph.nodes()) # edge cases: if total_of_nodes in (0, 1): return min_cut # contraction loop (need to contract len-2 times to reach 2 nodes) for nodes_count in reversed(range(3, total_of_nodes + 1)): # i. Pick a remaining edge (u,v) uniformly at random. v, u = rchoice(tmp_graph.edges()) # ii. Merge (or “contract”) u and v into a single vertex. # iii. Remove self-loops tmp_graph.merge_nodes(v, u) # result passing total_of_nodes = len(tmp_graph.nodes()) if total_of_nodes is 2: min_cut = len(tmp_graph.edges()) return min_cut else: print("Error in rcontract_min_cut") return min_cut return min_cut
def rcontract_min_cut(self): """ David Karger's '90s Random Contraction Algorithm - While there are more than 2 vertices: i. Pick a remaining edge (u,v) uniformly at random. ii. Merge (or “contract”) u and v into a single vertex. iii. Remove self-loops - Return cut represented by final 2 vertices. """ min_cut = 0 tmp_graph = deepcopy(self) total_of_nodes = len(tmp_graph.nodes()) # edge cases: if total_of_nodes in (0, 1): return min_cut # contraction loop (need to contract len-2 times to reach 2 nodes) for nodes_count in reversed(range(3, total_of_nodes+1)): # i. Pick a remaining edge (u,v) uniformly at random. v, u = rchoice(tmp_graph.edges()) # ii. Merge (or “contract”) u and v into a single vertex. # iii. Remove self-loops tmp_graph.merge_nodes(v, u) # result passing total_of_nodes = len(tmp_graph.nodes()) if total_of_nodes is 2: min_cut = len(tmp_graph.edges()) return min_cut else: print("Error in rcontract_min_cut") return min_cut return min_cut
def _newPrimaryKey(self): '''Return a new random string for use as a primary key.''' N = 20 chars = string.ascii_uppercase + string.digits pk = [rchoice(chars) for _ in range(N)] pk = ''.join(pk) return pk
def genrand(): n = random() if n <= 0.1: return wildcard elif n <= 0.1025: return dunce else: return rchoice(normtiles)
def symcolrhexcodes(symbols): """ returns dict of color codes mapped with alphabets symbol in symbols """ return { symbol: '#' + ''.join([rchoice("8A6C2B590D1F4E37") for _ in "FFFFFF"]) for symbol in symbols }
def _select_topic(self, mode): if mode == "old": tid = rchoice(list(self.settings["topics"].keys())) elif mode == "new": tid = self.settings["topic_queue"].pop() dataIO.save_json(self.path, self.settings) else: tid = mode return self.settings["topics"][tid]["content"]
def handle_turn_ai(player): number_list = list(range(9)) valid = True while valid: choice_ai = rchoice(number_list) number_list.remove(choice_ai) if board[choice_ai] == "-": valid = False board[choice_ai] = player
def insert_blanks(s, min_chars=32, max_chars=128): """ Inserts random zero width characters in the given string This is useful for avoiding filters """ for _ in range(1, randint(min_chars, max_chars)): i = randint(0, len(s)) s = s[:i] + rchoice(blanks) + s[i:] return s
def give_name(self): """ Randomizer function to give an entity a random name. Arbitrary amounts of names can be added to these arrays. """ if self.gender == "male": self.name = rchoice([ "albert", "brutus", "chris", ]) if self.gender == "female": self.name = rchoice([ "ally", "beatrix", "chloe", ])
def anonymize(masking): i = 0 for rec in SeqIO.parse(sys.stdin, "fastq"): rec.id, rec.description, i = make_id(i) if masking: rec.seq = Seq.Seq(len(rec) * 'N') else: rec.seq = Seq.Seq(''.join( [rchoice(['A', 'C', 'T', 'G']) for i in range(len(rec))])) print(rec.format("fastq"))
def get_random_movie(): addr = r"https://www.themoviedb.org/movie" resp = requests.get(addr) soup = BeautifulSoup(resp.content, "html.parser") titles = [] for header in soup.find_all("h2"): for link in header.find_all("a"): titles.append(link.get("title")) return rchoice(titles)
def get_choice(self, features): if random.random() < self.options['explore']: return rchoice(range(self.num_choices)) else: feats = np.array(features).reshape(1, 2) probs = [ model.predict_proba(feats)[0] for model in self.choice_models ] probs = [prob[1] if len(prob) == 2 else prob[0] for prob in probs] return np.argmax(probs)
def _into_sentence(s: Sentence, prefix: list[int], conn_dict: dict[int, tp.Iterable[str]], variables: list[str]): l = prefix[0] if l == 0: s.append(rchoice(variables)) else: possible_main = conn_dict[l] main = s.generate(rchoice(possible_main)) if l == 2: # INFIX s.append('(') _into_sentence(s, prefix[1:], conn_dict, variables) s.append(main) _into_sentence(s, prefix[1:], conn_dict, variables) s.append(')') else: s.append(main) for _ in range(l): _into_sentence(s, prefix[1:], conn_dict, variables)
def get_profile_image(name): default = { 'title': name, 'source': default_media, } profile = next((i for i in user_media if i['title'] == name), default) medID = rchoice(random_ids) random_ids.remove(medID) profile['mediaId'] = str(medID) profile['type'] = "profile-image" requests.post(local_url + 'media', json=json.dumps(profile)) return profile
def advance(self): """Step forward one step in time.""" # log data BEFORE manipulating the population if MATH.remainder(MATH.int(self.time),self.sampGen) == 0: self.notify(time=self.time) # first select a round of parents parents = [self.select_parent(method=self.selectionMethod) for x in xrange(self.forestSize)] offspring = list() if not self.elitism: for i in xrange(0, self.forestSize): offspring.append(self.mate(rchoice(parents),rchoice(parents))) else: fitvals = MATH.asarray([x.fitness for x in self.population]) toCopy = fitvals.argsort()[-self.eliteN:] offspring += [self.population[x].copy() for x in toCopy] # now mate to create the remaining population for i in xrange(0, self.forestSize-self.eliteN): offspring.append(self.mate(rchoice(parents), rchoice(parents))) # overwrite current forest self.population = offspring # advance time self.time += 1
def get_trajectories(): test = read_from_src_edgelist_to_idvalue() unprocessed = set([i + 1 for i in range(len(test))]) final = [] while len(unprocessed) > 0: current = traverse(rchoice(list(unprocessed)), test) unprocessed.difference_update(current) # print(unprocessed) final.append(list(current)) #print("final =", final) return final
def readFBDataSet(): fileNames = [ os.path.join('datasets', 'messages', f, 'message.json') for f in os.listdir(os.path.join('datasets', 'messages')) ] messages = "" while len(messages) < MAX_CHAT_LENGTH: messages += loadSimpleMessageSet(loadSimpleJson(rchoice(fileNames))) print(len(messages), ' chars loaded for trainings') return messages
def select_parent(self,method,**kwargs): """A dispatcher that implements a variety of selection methods and returns a single parent to place in the pool for the next generation. Current allowed methods (all strings): -'tournament' : requires a parameter k. two individuals are chosen at random; if rand < k, the fitter individual is selected. if rand > k, the less fit one is. Regardless of selected method, the parent is returned as a CGAChromosome object.""" mstring = method + '_selection' if hasattr(self, mstring): parent = getattr(self,mstring)(**kwargs) else: parent = rchoice(self.population) # pick at random if there's a problem return parent
def random(session): # useful only when you have a lot of stories (obviously) days = range((datetime.now() - session.birthday).days + 1) for i in range(25): # try 25 times _story_exists, date = session.find_stories(session.birthday + timedelta(rchoice(days))) if not date: break story = Story(session, date) if story.get_path(): return story.view() print ERROR, "Looks like you don't have much stories in the given location!"
def main(argv): if len(argv)==2: global K = int(argv[0]) global COEFFICIENT = float(argv[1]) result_f = codecs.open('data/result.txt', 'w+','utf-8') start = time.clock() i = 1 with codecs.open('data/queries.txt', 'r','utf-8') as f: for line in f: res = line.split('\t') category = res[6] user = res[1] query = res[2]+ '\t'+ res[3]+ '\t'+ res[4]+ '\t'+ res[5] if not category in data: data[category] = [K, [], []] # [MAX_QUERIES, USERS, QUERIES] curcat = data[category] curcat[1].append(user) curcat[2].append(query) if len(curcat[1])>=curcat[0]: #Category full query_choice = rchoice(curcat[2]) if curcat[1].count(query_choice[0]) >= curcat[0]: # All users are the same curcat[0] = curcat[0]*COEFFICIENT else: user_choice = rchoice(curcat[1]) while user_choice==query_choice[0]: # Find a different user user_choice = rchoice(curcat[1]) result_f.write(query_choice[2] + '\t'+user_choice+'\t'+query_choice[1]+'\n') curcat[1].remove(user_choice) curcat[2].remove(query_choice) i+=1 mem = asizeof.asizeof(data) total=time.clock()-start result_f.close()
def makeSimilarStatus(status, generator): choices = [generator() for i in range(250)] status = set(letters_and_whitespace(status).lower().split()) common = set(['a', 'in', 'the', 'and', 'to', 'do', 'are', 'you', 'so', 'is', 'of']) status = status - common best_choice = rchoice(choices) best = 0 for choice in choices: choice = choice.split('.')[0] match = set(letters_and_whitespace(choice.lower()).split()) & status if len(match) > best: best = len(match) best_choice = choice print(best_choice, match) return best_choice
def traverse(offset_start, source_graph): current_trajectory = set() next_index = offset_start - 1 #print(f"next_number = {next_index + 1}") options = source_graph[next_index][2] #print(f"options = {options}") while not set(options).issubset(current_trajectory): current_trajectory.add(next_index + 1) next_index = rchoice(options) - 1 #print(f"next_number = {next_index + 1}") options = source_graph[next_index][2] #print(f"options = {options}") if len(current_trajectory) < 3: current_trajectory = traverse(next_index, source_graph) return current_trajectory
def get_choice(self, request_method, url, **kwargs): cho = [] while True: try: cho = rchoice(self.new_address) choice = {'https': cho} print('Proxy currently being tested: {}'.format(choice)) response = requests.request(request_method, url, proxies=choice, timeout=10, **kwargs) if response.status_code == 200: print('Current proxy is functional.') break except: print('Error: Could not connect, looking for another proxy.') self.new_address.remove(cho) pass
def __init__(self): """ Initialize all essential values here, make sure that more complex values are set to some undifined state, then call a function that sets them. """ # Basic assignments here self.gender = rchoice(["male", "female"]) self.name = "undefined" self.id = gen_uuid4() self.skills = {"undefined": True} self.vitals = {"undefined": True} self.stats = {"undefined": True} self.position = {"x": 0, "y": 0, "z": 0} # List of functions to set more complex characteristics self.give_name() self.initialize_skills() self.initialize_stats() self.initialize_vitals()
def index(request): ''' index page view ''' possibleWords = [ # these are that get chosen on the home page " smarter", " better", " brilliant", " genius", "n amazing", " superior", ] # checking if word has already been chosen if request.session.get("homepageWord") in [None, "", "None"]: # choosing word and setting session var request.session["homepageWord"] = rchoice(possibleWords) # rendering index page request.session['page'] = 'Home' return render(request, 'index.html')
def download_stocks(symbol: str = None, dl_path: str = None, proxies_path: str = None, interval_arg: str = None): """Fetches stocks csv's on yahoo finance. Args: symbol: Symbol of the stock to be downloaded dl_path: Filepath to indicate where to store the downloaded stocks. proxies_path: Filepath to indicate the proxies to take interval_arg: Interval of the stock to be downloaded """ stock_path = f'{dl_path}/{symbol}_{interval_arg}.csv' if os.path.isfile(stock_path) == True: return stock_path if proxies_path is not None: proxies = _get_proxies(proxies_path) stock_name = os.path.join(dl_path, symbol + '_' + interval_arg + '.csv') if proxies_path is not None: proxy = rchoice(proxies) print(f'Downloading {symbol} on proxy {proxy} ...') stock = yf.download(symbol, proxy=proxy, period='max', interval=interval_arg) else: print(f'Downloading {symbol} on proxy 0.0.0.0 ...') stock = yf.download(symbol, period='max', interval=interval_arg) if stock.shape[0] > 2: if list(("1wk", "1mo", "3mo")).count(interval_arg) > 0: stock = stock[0:len(stock) - 1] stock.to_csv(stock_name) print(f'Successfully Downloaded stock {symbol} !') return stock_path else: print(f'Couldn\'t download stock {symbol}') return None
def mate(self, parentOne, parentTwo): """Accepts two parents and returns ONE offspring; if the offspring is unchanged from one of the parents, the fitness values are not re-evaluated, just copied. Only one category of mutation is performed on a single offspring.""" # one parent will form the basis for the new offspring; the other is just there for # potential crossover (by default the mother will become the offspring) mother, father = parentOne.copy(), parentTwo.copy() # fitEval will be set to True if any mutations occur that make the offspring different from # its copied parent; this way we avoid unnecessary fitness evaluations fitEval = False # only one category of mutation is allowed per mating event r = urand() if r < self.pC: # parental crossover fitEval = True mNode = rchoice(mother.tree.getNodes()) fNode = rchoice(father.tree.getNodes()) CGAGenerator.single_crossover(mNode,fNode) elif r < self.pC + self.pHC: # headless chicken crossover fitEval = True mNode = rchoice(mother.tree.getNodes()) rNode = rchoice(self.initialize_tree().getNodes()) CGAGenerator.single_crossover(mNode,rNode) elif r < self.pC + self.pHC + self.pM: # point mutation (uses pM/node for mutation prob.) fitEval = True for n in mother.tree.getNodes(): if urand() < self.pM: CGAGenerator.point_mutate(mother.tree, n) fitEval = True elif r < self.pC + self.pHC + self.pM + self.pP: # pruning - guaranteed to do one pruning operation fitEval = True mNode = rchoice(mother.tree.getNodes()) CGAGenerator.prune(mother.tree,mNode) elif r < self.pC + self.pHC + self.pM + self.pP + self.pG: # growth - guaranteed to do one growth op. fitEval = True mTerm = rchoice(mother.tree.getTermini()) CGAGenerator.grow(mother.tree,mTerm) else: # offspring will just be a copy pass if fitEval: mother.fitness,mother.parsimony,mother.finitewts = self.evaluate_fitness(mother.tree) return mother
deepBlue = (0,62,142) wordCho1=rchoice(words) wordCho2=rchoice(words2) draw.text( (430, 282), wordCho1, font=font, fill=deepBlue ) draw.text( (928, 282), wordCho2, font=font, fill=deepBlue ) drawCenterText(data[pos1]['name'], (85,480)) drawCenterText(data[pos2]['name'], (608,480)) return bg jsonData=u'[{"name":"鰹魚調味料","promo":"該品牌單筆指定品滿150送15現金紅利","url":"http://www.savesafe.com.tw/Products/ProductView.aspx?s_id=f9897fe9bacfb5f718bf711e7a1d738b"},{"name":"靠得住","promo":"大促銷$149元","url":"http://www.savesafe.com.tw/Products/ProductView.aspx?s_id=bf19a2a50bb1208b257ac4c6fd5c91c0"},{"name":"100%純橄欖油","promo":"","url":"http://www.savesafe.com.tw/Products/ProductView.aspx?t_s_id=43013&s_id=717123634b662e150798d4667d3c6047"},{"name":"青蔥蘇打餅乾","promo":"","url":"http://www.savesafe.com.tw/Products/ProductView.aspx?t_s_id=41592&s_id=4266242f39cfc67bda72e62f7e050b92"},{"name":"堅果山核桃","promo":"熱賣商品","url":""},{"name":"鮮奶油","promo":"熱賣商品","url":""},{"name":"紅燒鰻","promo":"","url":"http://www.savesafe.com.tw/Products/ProductView.aspx?s_id=9684a1353c4b44f0342ac73cf2da1d46"}]' words = [u'加上', u'混合', u'搭配'] words2 = [u'好棒棒', u'好厲害', u'猴塞雷', u'好有事', u'搖一搖', u'好壞壞', u'真好人', u'好勵志', u'就甘心'] data=json.loads(jsonData) rset=range(0, len(data)) mylist = range(len(data)) res=0 while mylist: choice1 = rchoice(mylist) mylist.remove(choice1) if mylist: choice2 = rchoice(mylist) mylist.remove(choice2) img = generateImg(data, choice1, choice2) res+=1 img.save("result/r"+str(res)+".jpg")