2016-08-22 68 views
-1

我在這裏要做的是寫一個文本文件,如果它還沒有存在的小寵物的發現的經緯度。由於我使用的是無限循環,因此我添加了一個if-state來防止已經存在的一對座標被添加。 請注意,我也有一個存儲相同信息的列表座標。該列表的工作原理是不添加重複(通過檢查)但是,文本文件具有相同的座標,即使它理論上不應該如同包含在與列表相同的if塊中。If語句看起來被寫操作忽略

import requests 

pokemon_url = 'https://pogo.appx.hk/top' 

while True: 
    response = requests.get(pokemon_url) 
    response.raise_for_status() 

    pokemon = response.json()[0:] 

    Sighting = 0 
    Coordinates = [None] * 100 

    for num in range(len(pokemon)): 
     if pokemon[num]['pokemon_name'] == 'Aerodactyl': 
      Lat = pokemon[num]['latitude'] 
      Long = pokemon[num]['longitude'] 
      if (Lat, Long) not in Coordinates: 
       Coordinates[Sighting] = (Lat, Long) 
       file = open("aerodactyl.txt", "a") 
       file.write(str(Lat) + "," + str(Long) + "\n") 
       file.close() 
       Sighting += 1 

爲了清楚起見,這是輸出 For clarity purposes, this is the output

+0

這段代碼是完全搞砸了。 'while True'循環永遠不會退出,並且在'file.close'調用之後忘記添加一對括號。 – xmcp

+0

'for'循環應該在while循環中嗎? – Barmar

+0

我推薦一個'set()'來代替列表的座標。 –

回答

2

你需要把while循環之外你SightingCoordinates變量,如果你不希望他們在每次迭代復位。

但是,代碼還有很多錯誤。沒有嘗試它,這裏是我發現的:

  1. 您沒有while循環的退出條件。請不要這樣做到窮人的網站。你基本上會發送垃圾郵件請求。
  2. file.close應該是file.close(),但總體而言,您只需要打開一次文件,而不是循環的每一次迭代。打開一次,完成後關閉(假設您將添加退出條件)。
  3. 0response.json()[0:])切片是不必要的。默認情況下,列表從索引0開始。這可能是一個複雜的方式來獲得一個新的列表,但這似乎沒有必要。
  4. Coordinates不應該是硬編碼列表100 None s。只需使用set即可追蹤現有座標。
  5. 完全擺脫Sighting。如果你一遍又一遍地重新發出請求,這是沒有意義的。如果你想從一個響應迭代神奇寶貝,如果你需要索引,使用enumerate
  6. 對於Python變量使用snake case通常是很好的做法。
+0

他每次關閉文件的原因都是因爲無限循環。他按Ctl-c結束循環。 – Barmar

+0

謝謝。我意識到這是糟糕的編碼,但我只是學習從網頁上取消數據。 –

+0

@ShermanSze不客氣 - 我們都在這裏學習:) – Karin

0

試試這個:

#!/usr/bin/env python 

import urllib2 
import json 

pokemon_url = 'https://pogo.appx.hk/top' 

pokemon = urllib2.urlopen(pokemon_url) 

pokeset = json.load(pokemon) 

Coordinates = [None] * 100 

for num in range(len(pokeset)): 
    if pokeset[num]['pokemon_name'] == 'Aerodactyl': 
     Lat = pokeset[num]['latitude'] 
     Long = pokeset[num]['longitude'] 
     if (Lat, Long) not in Coordinates: 
      Coordinates.append((Lat, Long)) 
      file = open("aerodactyl.txt", "a") 
      file.write(str(Lat) + "," + str(Long) + "\n") 
      file.close