2016-11-13 40 views
0

首先,對於牆壁文本,感到抱歉。我儘可能地解釋這個問題。每次滿足條件時運行一段代碼

你好,從標題你可能認爲我指的是一個簡單的if聲明,這可能是正確的。我今天對這個項目做了一些問題,現在我想做其他事情。我正在使用英雄聯盟進行一個機器人。機器人所做的只是從當前某個玩家的遊戲中打印一些數據。對於那些不熟悉遊戲的人來說,這裏有排名。排名是機器人在正在處理的聊天中打印的統計數據之一;這些數據來自排名遊戲,與普通遊戲不同,排名遊戲是統計這些數據的遊戲。無論如何;我以json的形式獲取數據,並且每當玩家未排序時(不排名玩家),我從請求中獲得404,並且我想處理404以打印其他內容。眼下,這是代碼的重要組成部分:

  ids_seen = set() 
      for y in range(0, 10): 
       num += 1 
       i = r_match['participants'][num] 
       e_name = i['summonerName'] 
       e_id = i['summonerId'] 
       team_id = i['teamId'] 
       champ = i['championId'] 

       r_team = requests.get("https://lan.api.pvp.net/api/lol/lan/v2.5/league/by-summoner/{}/" 
             "entry?api_key=".format(e_id)).json() 

       champ_r = requests.get("https://global.api.pvp.net/api/lol/static-data/lan/v1.2/champion?" 
             "api_key=").json() 

       x = r_team["{}".format(e_id)][0] 
       e_tier = x['tier'] 
       e_div = x['entries'][0]['division'] 

       for key, value in champ_r['data'].items(): 
        c_name = value['name'] 
        c_id = value['id'] 

        chat_say = """ 
{} - {} {} - Playing `#{}`""".format(e_name, e_tier, e_div, c_name) 

        if champ == c_id: 
#       if r_team['status']['status_code'] == 404: 
#        unranked_term = (e_name + " - " + "Unranked") 
#        unranked_say = """ 
# {} - Playing `#{}`""".format(unranked_term, c_name) 
#        yield from bot.send_message(message.channel, unranked_say) 

         # else: 
          if team_id == 100: 
           if not team_id in ids_seen: 
            yield from bot.send_message(message.channel, "```---Blue team---```") 
           yield from bot.send_message(message.channel, chat_say) 

          elif team_id == 200: 
#         if r_team['status']['status_code'] == 404: 
#          unranked_term = (e_name + " - " + "Unranked") 
#          unranked_say = """ 
# {} - Playing `#{}`""".format(unranked_term, c_name) 
#          yield from bot.send_message(message.channel, unranked_say) 

           if not team_id in ids_seen: 
            yield from bot.send_message(message.channel, "```--- Red team ---```") 
           yield from bot.send_message(message.channel, chat_say) 

       ids_seen.add(team_id) 

       yield from asyncio.sleep(1) 

當我運行這段代碼的輸出是這樣的:

Player1 - Rank - Champion that is being played 
Player2 - Rank - Champion that is being played 
Player3 - Rank - Champion that is being played... 

...等;但是如果發現像我之前提到的那樣沒有排名的球員,那麼就會發生KeyError,因爲它無法在json上找到任何排名數據。所以;我評論了一些我想要實現的內容。

此:

#       if r_team['status']['status_code'] == 404: 
#        unranked_term = (e_name + " - " + "Unranked") 
#        unranked_say = """ 
# {} - Playing `#{}`""".format(unranked_term, c_name) 
#        yield from bot.send_message(message.channel, unranked_say) 

我試圖把這個它的確切位置。我也得到一個KeyError;如果我把它放在這裏:

    if team_id == 100: 
          # <- Right here if I'm not wrong. 
         if not team_id in ids_seen: 
          yield from bot.send_message(message.channel, "```---Blue team---```") 
         yield from bot.send_message(message.channel, chat_say) 

我得到的球員和冠軍正在播放,但每一個的行列顯示爲未排序;每個人都沒有排名。問題是,我如何將其實現到我的代碼?我不確定我是否在正確的道路上這樣做。

我想輸出是這樣的:

Player1 - Rank - Champion # If it has ranked information 
Player2 - Rank - Champion # Same 
Player3 - Unranked - Champion # If the player is unranked 

一切都是這樣我就可以正常運行的機器人,因爲每次有一個未排序我得到一個錯誤,我只是無法避免(除非找到沒有未排名球員的比賽)

感謝您的幫助! :)

回答

0

你可以嘗試在您得到一個KeyError的確切位置添加try except block,這將嘗試在該鍵來獲取值,如果不存在的話,它會趕上exception它不存在並且如你所願(在你的情況下,便陷入困境的球員)

例如,你可以處理這個exception - 如果這是你的JSON或你的字典

jsonobj = { 
    "players":[ 
     { 
     "rank":"500", 
     "name":"IAMRANKED" 
     }, 
     { 
     "name":"IAMNOTRANKED" 
     } 
    ] 
} 

那麼,如果你有一個try except塊般的環繞它這個:

# EXAMPLES 
try: 
    print(jsonobj['players'][0]['rank']) #SURROUND YOUR ASSIGNEMENT WITH A TRY CATCH BLOCK 
    print("I have a rank") # WILL PRINT RANK EXISTS 
except KeyError: 
    print("I do not have a rank") 

try: 
    print(jsonobj['players'][1]['rank']) 
    print("I have a rank") 
except KeyError: 
    print("I do not have a rank") # WILL PRINT RANK DOES NOT EXIST 

希望這有助於!

+0

嗨@fuhrerguxez如果這或任何答案已解決您的問題,請考慮[接受它](http://meta.stackexchange。com/q/5234/179419)通過點擊複選標記。這向更廣泛的社區表明,您已經找到了解決方案,併爲答覆者和您自己提供了一些聲譽。沒有義務這樣做。 –

+0

你好,我確實需要的只是一個嘗試......除了塊之外,我有一個,但它被錯誤地放置。經過一些調整後,我得到了它的工作,謝謝! – Aguxez