Beispiel #1
0
    def control_players(self):
        """Executes main control flow for player turns

        RAISES
            Exception if one occurs
        """
        try:
            rules = Rules(self.deck, 0)
            same_player = True
            wincondition = False

            while wincondition == False:
                for hand in self.hands:
                    same_player = True
                    self._active = self.hands[hand][0]
                    while same_player == True:
                        print("you: %s" % hand)
                        choice = self.choose_hand(hand)
                        self.hands[hand][0].visi_override()
                        if rules.play_game(self.hands[hand][0], self.hands[choice][0]) == False:
                            same_player = False
                            self.hands[hand][1] += rules.points
                        else:
                            self.hands[hand][1] += rules.points
                            same_player = True
                    if self.empty_hands == self.hand_count:
                        wincondition = True
        except:
            Error.log_error(sys.exc_info()[1], "Game.control_players()")
Beispiel #2
0
def connect_four():
    """ 
    This function plays the connect four game is the main function 
    of this project.

    Input: None
    Output: Winner of the Connect 4 Game
    """
    board, player_one, player_two = init_game()
    game_in_progress = True
    curr_player = player_one
    winner = None
    while game_in_progress and mp.full_board(board) == False:
        gui.display_board(board)
        if curr_player == ai_player:
            position = mc.next_move(board, curr_player)
        if curr_player == other_player:
            position = mp.random_next_move(board, curr_player)
        if rules.won_game(board, position, curr_player):
            game_in_progress = False
            winner = curr_player
            if winner == ai_player:
              gui.create_message(f'AI Player has won Connect Four!')
            if winner == other_player:
                gui.create_message(f'Other Player Two won Connect Four!') 
        gui.display_board(board)
        curr_player = rules.get_opponent(curr_player)
    # time.sleep(10)
    return winner
Beispiel #3
0
 def test_function_player_answer_yes(self):
     rules = Rules()
     hand = Hand()
     card = Card(rank=Rank.ACEHIGH, suit=Suit.DIAMONDS)
     hand += card
     self.assertEqual(rules.player_answer(Rank.ACEHIGH, hand), "YES",
                      "player answer Not returning YES when it should")
Beispiel #4
0
	def rulesthread(self):
		start = time.time()
		if (self.suanfa=='Aprioi'):
			if(self.minconfig!=0):
				self.rules=apriori.generateRules(self.L,self.support,self.minconfig)
			else:
				self.rules=apriori.generateRules(self.L,self.support)
		else:
			self.rules = []
			if (self.minconfig!=0):
				Rules.rulesGenerator(self.L, self.rules, self.minconfig)
			else:
				Rules.rulesGenerator(self.L, self.rules)
		# self.rules = []
		# if (self.minconfig!=0):
		# 	Rules.rulesGenerator(self.L, self.rules, self.minconfig)
		# else:
		# 	Rules.rulesGenerator(self.L, self.rules)
		self.result_data_Text.insert(INSERT,'关联规则\n')
		for i in self.rules:
			self.result_data_Text.insert(INSERT,list(i))
			self.result_data_Text.insert(INSERT,'\n')
		end = time.time()
		self.result_data_Text.insert(INSERT,str(len(self.rules))+'\n')
		self.log_data_Text.insert(INSERT,'关联规则生成完毕! 共'+str(len(self.rules))+'项	耗时:'+str(round(end-start,2))+'s\n')
Beispiel #5
0
 def test_function_book_check_fullbook(self):
     rules = Rules()
     hand = Hand()
     for s in Suit:
         hand.add_card(Card(rank=Rank.THREE, suit=s))
     self.assertEqual(rules.book_check(Rank.THREE, hand), 4,
                      "book check not finding book")
Beispiel #6
0
def tst(packet):
    ip_laye = packet.getlayer(IP)
    protocol = ip_laye.get_field('proto')
    # print(ip_laye[1].src)
    #print('src:{}\nsrc_port:{}\nprotocol:{}\ndst:{}\ndst_port:{}\n'.format(ip_laye.src,ip_laye.sport,protocol.i2s[packet.proto],ip_laye.dst,ip_laye.dport))
    global src_ip
    global paketler
    global raw_data
    src_ip = str(ip_laye.src)
    dst_ip = str(ip_laye.dst)
    src_port = str(ip_laye.sport)
    dst_port = str(ip_laye.dport)
    raw_data = packet.payload

    global veri
    if dataset_Create:
        protokol = str(protocol.i2s[packet.proto])
        base['src ip'].append(src_ip)
        base['src port'].append(src_port)
        base['protocol'].append(protokol)
        base['dst ip'].append(dst_ip)
        base['dst port'].append(dst_port)
        paketler = ('--> src: ' + src_ip + ' dst: ' + dst_ip + ' sport: ' +
                    src_port + ' dport: ' + dst_port + ' proto: ' + protokol +
                    ' --> ' + str(ip_laye.summary()))
        paket_lst.append([paketler, raw_data])
        veri = pd.DataFrame(base)
        check.check_packet(src_ip, src_port, protokol, dst_ip, dst_port)

        label_data()

        #dataframei parcala
        #print(veri.iloc[2:,2:3])
    else:
        print(packet.summary())
 def setDefault(self):
     '''
     ''' 
     wdgt = self.dictFields['fldWidget']
     toDefault = self.dictFields['toDefault']
     for idx, val in enumerate(wdgt):
         if toDefault[idx]:
             Rules.setNull(wdgt=val)
Beispiel #8
0
def get_intention():
    print(request.form["utt"])
    print(request.form["user_key"])
    model = Rules.Model(request.form)

    res = Rules.make_response(model)
    print(res)
    return json.dumps(res)
Beispiel #9
0
 def test_function_check_deck_10pop(self):
     deck = Deck(ace_rank=Rank.ACELOW)
     rules = Rules(deck=deck)
     hand = Hand()
     for i in range(10):
         hand += deck.deal()
     self.assertEqual(rules.check_deck(), 42,
                      "Deck not showing 42 cards after dealing 10")
Beispiel #10
0
    def mainTestInteractive(self, sess):
        """ Try predicting the sentences that the user will enter in the console
        Args:
            sess: The current running session
        """
        # TODO: If verbose mode, also show similar sentences from the training set with the same words (include in mainTest also)
        # TODO: Also show the top 10 most likely predictions for each predicted output (when verbose mode)
        # TODO: Log the questions asked for latter re-use (merge with test/samples.txt)

        print('Testing: Launch interactive mode:')
        print('')
        print('Welcome to the interactive mode, here you can ask to Deep Q&A the sentence you want. Don\'t have high '
              'expectation. Type \'exit\' or just press ENTER to quit the program. Have fun.')

        import Rules
        import winsound

        while True:
            question = input(self.SENTENCES_PREFIX[0])

            if question == '' or question == 'exit':
                break

            ########## MY CODE ##########
            text_answer = Rules.search_for_answer(question) #On regarde si dialogueFlow donne une reponse
            if text_answer.upper() != "NEGATIVE":
                print(self.SENTENCES_PREFIX[1], text_answer)
                #Pour garantir que ça marche on fait ça quand meme :
                questionSeq = []  # Will be contain the question as seen by the encoder
                answer = self.singlePredict(question, questionSeq)
                if not answer:
                    continue  # Back to the beginning, try again
                #
            else: #sinon on active le DeepBot
            #############################

                questionSeq = []  # Will be contain the question as seen by the encoder
                answer = self.singlePredict(question, questionSeq)
                if not answer:
                    print('Warning: sentence too long, sorry. Maybe try a simpler sentence.')
                    continue  # Back to the beginning, try again

                print('{}{}'.format(self.SENTENCES_PREFIX[1], self.textData.sequence2str(answer, clean=True)))

            ########## MY CODE ##########
                text_answer=str(self.textData.sequence2str(answer, clean=True))

            Rules.speech_synthesis(text_answer) #On cree le fichier audio
            winsound.PlaySound('output.wav', winsound.SND_FILENAME) #On le joue
            #############################



            if self.args.verbose:
                print(self.textData.batchSeq2str(questionSeq, clean=True, reverse=True))
                print(self.textData.sequence2str(answer))

            print()
Beispiel #11
0
 def test_function_count_request_2(self):
     rules = Rules()
     hand = Hand()
     hand += [
         Card(rank=Rank.THREE, suit=Suit.DIAMONDS),
         Card(rank=Rank.THREE, suit=Suit.SPADES)
     ]
     self.assertEqual(
         rules.count_request(hand, Rank.THREE), 2,
         "count request not returning 2 for hand with two rank matches")
    def test_And(self):
        node =  Tokenization.SentenceNode("abc")
        node.features.add(FeatureOntology.GetFeatureID('NN'))
        strtokenlist = Tokenization.SentenceLinkedList()
        strtokenlist.append(node)

        self.assertFalse(LogicMatchFeatures(strtokenlist, 0, "NN percent", [Rules.RuleToken()], 0))

        node.features.add(FeatureOntology.GetFeatureID('percent'))
        self.assertTrue(LogicMatchFeatures(strtokenlist, 0, "NN percent", [Rules.RuleToken()], 0))
Beispiel #13
0
	def capturePlanet(self, tran, obj, planet):
		# find distance to closes pirate's planet
		dist = self.distToNearestPiratePlanet(tran,obj,planet)
		if random.random() <= Rules.pirateGainFamePropability(dist):
			log.debug(obj.oid, "Pirate captured planet + fame", dist, planet.oid)
			obj.pirateFame += Rules.pirateCaptureInRangeFame
			Utils.sendMessage(tran, obj, MSG_GAINED_FAME, planet.oid, Rules.pirateCaptureInRangeFame)
		elif random.random() <= Rules.pirateLoseFameProbability(dist):
			log.debug(obj.oid, "Pirate captured planet OUT OF range", dist, planet.oid)
			obj.pirateFame += Rules.pirateCaptureOutOfRangeFame
			Utils.sendMessage(tran, obj, MSG_LOST_FAME, planet.oid, Rules.pirateCaptureOutOfRangeFame)
Beispiel #14
0
 def configRules(self):
     self.dictRules = {}
     bok_w, matWdgt = Rules.getRules_Wdgt()
     bok_f, matfrm = Rules.getRules_Frm()
     if bok_w is True and bok_f is True:
         matfrm = Rules.splitObjectName(matxIn=matfrm)
         matOut = (matWdgt + matfrm)
         Rules.exeBuidAndFill(mainDict=self.dictRules,
                              matxOut=matOut,
                              matxWdgt=matWdgt,
                              matxFrm=matfrm)
Beispiel #15
0
def init_game():
    """
    This function initializes the game and displays the board.

    Input: None
    Output: The initialized board
    """
    board = mp.init_board()
    gui.display_board(board)
    player_one = rules.choose_turn()
    player_two = rules.get_opponent(player_one)
    return board, player_one, player_two
    def delete_data(self, list_fname):
        """
        Delete files from hdfs and insert hdfs path items into postgre
        """

        list_fname = ['test1.txt', 'test2.txt']

        ruler = Rules()
        list_hdfs_paths = ruler.path_rules(list_fname)

        flag = self.delete_hdfs_index(list_hdfs_paths)
        if flag is True:
            print("Delete" + str(list_hdfs_paths) + "from HDFS and Index successful!")
Beispiel #17
0
def fireRules(lineSegment,pDict):
    """Fire the extra rules ..."""
    
    
    components=lineSegment.split("@#@")
    
    rl=Rules(components[2],components[3])
    
    if rl.ruleNumbers() ==(True,"Number") :
        return True,"NumberRule","1"
    
    elif rl.ruleNumbers() ==(False,"Number") :
        return True,"NumberRule","0"
    
    if rl.ruleSame() :
        return True, "SameRule","1"
    
    if rl.ruleNameEntities() :
        return True, "NameEntitiesRule","1"
    
    if rl.ruleIdenticalLC(components,pDict) :
        return True,"LanguageRule","0"
    
    if rl.ruleCG() :
        return True,"ChurchGale","0"
    
    return False,"",""
def fireRules(components,pBatch):
    """Fire the extra rules ..."""
    
    source=components[2].encode('utf-8')
    target=components[3].encode('utf-8')
    
    #booolean,rule,value=fireExtraRules(source,target,pBatch)
    #if rule :
    #   return booolean,rule,value
    
    rl=Rules(source,target)
    
    if rl.ruleNumbers() ==(True,"Number") :
        return True,"NumberRule","1"
    
    elif rl.ruleNumbers() ==(False,"Number") :
        return True,"NumberRule","0"
    
    if rl.ruleSame() :
        return True, "SameRule","1"
    
    if rl.ruleNameEntities() :
        return True, "NameEntitiesRule","1"
    
    if rl.ruleIdenticalLC(components,pBatch) :
        return True,"LanguageRule","0"
    
    if rl.ruleCG() :
        return True,"ChurchGale","0"
    
    return False,"",""  
 def _verfVals(self):
     wdgt = self.dictFields['lstWidget']
     toDefault = self.dictFields['lstDefault']
     toUpercase = self.dictFields['lstUpercase']
     for idx, val in enumerate(wdgt):
         if toDefault[idx]:
             Rules.setNull(wdgt=val)
         if toUpercase[idx]:
             Rules.setUPPER(wdgt=val)
         if toDefault[idx] is False:
             bOK = Rules.notNull(wdgt=val)
             if bOK is False:
                 break
     return bOK
def fireRules(components, pBatch):
    """Fire the extra rules ..."""

    source = components[2]
    target = components[3]

    rl = Rules(source, target)

    if rl.ruleNumbers() == (True, "Number"):
        return True, "NumberRule", "1"

    elif rl.ruleNumbers() == (False, "Number"):
        return True, "NumberRule", "0"

    if rl.ruleSame():
        return True, "SameRule", "1"

    if rl.ruleNameEntities():
        return True, "NameEntitiesRule", "1"

    if rl.ruleIdenticalLC(components, pBatch):
        return True, "LanguageRule", "0"

    if rl.ruleCG():
        return True, "ChurchGale", "0"

    return False, "", ""
def fireRules(lineSegment, pDict):
    """Fire the extra rules ..."""

    components = lineSegment.split("@#@")
    source = components[2]
    target = components[3]

    booolean, rule, value = fireExtraRules(source, target, pDict)
    if rule:
        return booolean, rule, value

    rl = Rules(source, target)

    if rl.ruleNumbers() == (True, "Number"):
        return True, "NumberRule", "1"

    elif rl.ruleNumbers() == (False, "Number"):
        return True, "NumberRule", "0"

    if rl.ruleSame():
        return True, "SameRule", "1"

    if rl.ruleNameEntities():
        return True, "NameEntitiesRule", "1"

    if rl.ruleIdenticalLC(components, pDict):
        return True, "LanguageRule", "0"

    if rl.ruleCG():
        return True, "ChurchGale", "0"

    return False, "", ""
 def capturePlanet(self, tran, obj, planet):
     # find distance to closes pirate's planet
     dist = self.distToNearestPiratePlanet(tran, obj, planet)
     if random.random() <= Rules.pirateGainFamePropability(dist):
         log.debug(obj.oid, "Pirate captured planet + fame", dist,
                   planet.oid)
         obj.pirateFame += Rules.pirateCaptureInRangeFame
         Utils.sendMessage(tran, obj, Const.MSG_GAINED_FAME, planet.oid,
                           Rules.pirateCaptureInRangeFame)
     elif random.random() <= Rules.pirateLoseFameProbability(dist):
         log.debug(obj.oid, "Pirate captured planet OUT OF range", dist,
                   planet.oid)
         obj.pirateFame += Rules.pirateCaptureOutOfRangeFame
         Utils.sendMessage(tran, obj, Const.MSG_LOST_FAME, planet.oid,
                           Rules.pirateCaptureOutOfRangeFame)
Beispiel #23
0
def getPirateFameMod(tran, player, system):
	mod = 1.0
	for planetID in system.planets:
		planet = tran.db[planetID]        
		if getattr(planet, 'owner', OID_NONE) == player.oid:
			# minimum reached, don't check rest
			return 0.0
		elif getattr(planet, 'plStratRes', None) in (SR_TL3A, SR_TL3B, SR_TL3C):
			mod = min(mod, Rules.pirateTL3StratResColonyCostMod)
	dist = distToNearestPiratePlanet(tran, player, system)
	if Rules.pirateGainFamePropability(dist) > 0:
		mod = Rules.pirateColonyFameZoneCost(dist)
	else:
		mod = Rules.pirateColonyPlayerZoneCost(dist)
	return mod
Beispiel #24
0
def getPirateFameMod(tran, player, system):
    mod = 1.0
    for planetID in system.planets:
        planet = tran.db[planetID]
        if getattr(planet, 'owner', Const.OID_NONE) == player.oid:
            # minimum reached, don't check rest
            return 0.0
        elif getattr(planet, 'plStratRes', None) in (Const.SR_TL3A, Const.SR_TL3B, Const.SR_TL3C):
            mod = min(mod, Rules.pirateTL3StratResColonyCostMod)
    dist = distToNearestPiratePlanet(tran, player, system)
    if Rules.pirateGainFamePropability(dist) > 0:
        mod = Rules.pirateColonyFameZoneCost(dist)
    else:
        mod = Rules.pirateColonyPlayerZoneCost(dist)
    return mod
Beispiel #25
0
 def __loadFireWallRules(self):
     root = self.__getFireWallRulesRoot()
     self.rules = []
     for child in root.iter('entry'):
         self.rules.append(
             Rules(
                 self.__getRuleName(child),
                 self.__getRuleFrom(child),
                 self.__getRuleTo(child),
                 self.__getRuleSource(child),
                 self.__getRuleDestination(child),
                 self.__getRuleService(child),
                 self.__getRuleApplication(child),
                 self.__getRuleAction(child),
                 self.__getRuleSourceUser(child),
                 self.__getRuleDisableServerResponse(child),
                 self.__getRuleNegateSource(child),
                 self.__getRuleNegateDestination(child),
                 self.__getRuleDisabled(child),
                 self.__getRuleGroup(child),
                 self.__getRuleHipProfile(child),
                 self.__getRuleLogStart(child),
                 self.__getRuleLogEnd(child),
                 self.__getRuleDescription(child),
             ))
Beispiel #26
0
def insertuser(username, email, password):
    name = username.get()
    password = password.get()
    email = email.get()

    mydb = database()
    mycursor = mydb.cursor()
    sql = ("""SELECT * FROM user WHERE Name='%s'""" % name)
    mycursor.execute(sql)
    myresult = mycursor.fetchall()
    verifierResult = Rules.verifier(email, password)

    if verifierResult != 0 or len(myresult) >= 1:
        if verifierResult != 0 and len(myresult) >= 1:
            return verifierResult + " and Username is already taken"
        elif verifierResult == 0 and len(myresult) >= 1:
            return "Username is already taken"
        elif verifierResult != 0 and not len(myresult) >= 1:
            return verifierResult
    else:
        sql = "INSERT INTO user (Name, Password,Email) VALUES (%s, %s,%s)"
        val = (name, password, email)
        mycursor.execute(sql, val)
        mydb.commit()
        var = mycursor.rowcount
        return 1
    def test_LogicNotOr(self):
        """Logic And/Or"""
        node =  Tokenization.SentenceNode('d')
        strtokenlist = Tokenization.SentenceLinkedList()
        strtokenlist.append(node)

        RuleTokenList = [Rules.RuleToken()]

        self.assertFalse(LogicMatchFeatures(strtokenlist, 0, "!c|d|e", RuleTokenList, 0))
        node.text = "f"
        self.assertTrue(LogicMatchFeatures(strtokenlist, 0, "!c|d|e", RuleTokenList, 0))
        node.text = "e"
        self.assertTrue(LogicMatchFeatures(strtokenlist, 0, "!c d|e", RuleTokenList, 0))
        node.text = "f"
        self.assertFalse(LogicMatchFeatures(strtokenlist, 0, "!c d|e", RuleTokenList, 0))
        node.text = "c"
        self.assertTrue(LogicMatchFeatures(strtokenlist, 0, "c|d !d|e", RuleTokenList, 0))
        node.text = "d"
        self.assertFalse(LogicMatchFeatures(strtokenlist, 0, "c|d !d|e", RuleTokenList, 0))
        node.text = "e"
        self.assertFalse(LogicMatchFeatures(strtokenlist, 0, "c|e !d|f|g|e", RuleTokenList, 0))
        node.text = "e"
        self.assertFalse(LogicMatchFeatures(strtokenlist, 0, "c|d !d|c", RuleTokenList, 0))
        node.text = "f"
        self.assertFalse(LogicMatchFeatures(strtokenlist, 0, "c|d !d|e", RuleTokenList, 0))
Beispiel #28
0
 def generate_full_agents(self):
     self.ants = []
     self.rules = []
     for i in range(self.grid_size):
         for j in range(self.grid_size):
             self.ants.append(Ant(i , j))
             self.rules.append(Rules.generate_random_rules())
Beispiel #29
0
def set_led():
    f = request.form
    rgbw_tuple = (int(f.get('r')), int(f.get('g')), int(f.get('b')),
                  int(f.get('w')))

    db.set_rule(Rules.OneTimeRule(datetime.datetime.now(), rgbw_tuple))
    return "Success!"
Beispiel #30
0
def test_expansion(capsys):
    code = '''def trial357(param_0, param_1):
   op_lesser = param_0 < param_1
   return op_lesser'''
    test_input = [
        "a", "n", "y", "science", "lesser",
        "function determines the lesser of two objects", "y", "lesser",
        "name,op_lesser", "vars,2", "code,op_lesser = <var1> < <var2>",
        "return,return op_lesser", "end", "1,2", "test101", "trial357", "no"
    ]
    rules6 = Rules.Rules()
    exp = Expanding.Expands()

    def mock_input_6(s):
        #print(test_input)
        return test_input.pop(0)

    Rules.input = mock_input_6
    Expanding.input = mock_input_6
    out, err = capsys.readouterr()
    test = Rules.Rules.sentence_break(
        rules6, "I want a program to determine the lesser of two objects")
    mp = rules6.mp
    mp = mp.replace(" ", "")
    mp = mp.replace("\n", "")
    #print(mp)
    large = code.replace(" ", "")
    large = large.replace("\n", "")
    #print(large)
    assert mp == large
Beispiel #31
0
 def update_state(self, color, init_stone, init_move, aggro_stone,board_history=[]):
         self.board = [self.region0.stones, self.region1.stones, self.region2.stones, self.region3.stones]
         legality = Rules.Rules(self.board)
         updated_board= legality.update_board(color, init_stone, init_move, aggro_stone,board_history=[])
         print(updated_board)
         for region in self.regions:
             region.set_stones(updated_board[region.region_number])
    def test_LogicOr(self):
        """Logic Or"""
        node = Tokenization.SentenceNode('being')
        strtokenlist = Tokenization.SentenceLinkedList()
        strtokenlist.append(node)

        self.assertTrue(LogicMatchFeatures(strtokenlist, 0, "being|getting", [Rules.RuleToken()], 0))
Beispiel #33
0
def max_opponents_layout_score(layout, player):
    """
    This function determines the max score a player
    can achieve in the current turn if the goal
    is to play defensively.

    Input: The potential connect fours that can occur 
           represented as an array of anything within 
           four token width of the direction the function 
           was caled in. 
           The current player
    Output: The arbitrary score quantifying the likelyhood
            of the opponent scoring a connect 4.
    """
    opponent = rules.get_opponent(player)
    if layout.count(opponent) == 3:
        return 99999
    if layout.count(opponent) == 2 and layout.count(0) == 1:
        return 69
    if layout.count(opponent) == 1 and layout.count(0) == 2:
        return 29
    if layout.count(player) > 0:
        return 0
    else:
        return 1
Beispiel #34
0
 def generate_random_agents(self, nr_agents):
     self.ants = []
     self.rules = []
     for i in range(nr_agents):
         pos_x = rnd.randint(0, self.grid_size - 1)
         pos_y = rnd.randint(0, self.grid_size - 1)
         self.ants.append(Ant(pos_x , pos_y))
         self.rules.append(Rules.generate_random_rules())
Beispiel #35
0
 def generate_diagonal_agents(self, nr_agents):
     self.ants = []
     self.rules = []
     for i in range(nr_agents):
         range_start = i * self.grid_size / nr_agents
         range_end = (i + 1) * self.grid_size / nr_agents - 1
         pos_x = rnd.randint(range_start,range_end)
         pos_y = rnd.randint(range_start,range_end)
         self.ants.append(Ant(pos_x , pos_y))
         self.rules.append(Rules.generate_random_rules())
Beispiel #36
0
 def step(self, agent_index):
     ant = self.ants[agent_index]
     rule = self.rules[agent_index]
     current_state = self.get_cell_state(ant.x, ant.y)
     state, dx, dy = Rules.get_move(rule, current_state, ant.dx, ant.dy)
     if self.is_valid(ant.x + dx, ant.y + dy):
         ant.dx = dx
         ant.dy = dy
         self.set_cell(ant.x, ant.y, state)
         ant.x += dx
         ant.y += dy
Beispiel #37
0
     if x.lower() == "why":
         question_type="why"
         break
     if x.lower() == "how":
         for e,q_word in enumerate(q_li):
             if q_word.lower() == "how" and "how " + q_li[e+1] not in constants.ans_type:
                 question_type="how"
                 break
             if q_word.lower() == "how" and "how " + q_li[e+1] in constants.ans_type:
                 question_type="hownum"
                 break
 list1 = []
 dateline_score = 0
 if question_type=="who":
     for s in sent_list:
         score = Rules.whoRule(q,helper.remove_puncts(s))
         list1.append((s,score))
 elif question_type=="what":
     for s in sent_list:
         score = Rules.whatRule(q,helper.remove_puncts(s))
         list1.append((s,score))
 elif question_type=="when":
     dateline_score = Rules.datelineRule(q)
     for s in sent_list:
         score = Rules.whenRule(q,helper.remove_puncts(s))
         list1.append((s,score))
 elif question_type=="where":
     dateline_score = Rules.datelineRule(q)
     for s in sent_list:
         score = Rules.whereRule(q,helper.remove_puncts(s))
         list1.append((s,score))