我在这里要做的是,如果口袋妖怪还不存在的话,把它的纬度和经度写进一个文本文件。因为我使用的是一个无限循环,所以我添加了一个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
试试这个:
如果您不想在每次迭代时重置
Sighting
和Coordinates
变量,则需要将它们放在while
循环之外。你知道吗然而,代码有很多错误。不用尝试,我发现:
while
循环的退出条件。请不要这样对这个可怜的网站。你基本上是在发送垃圾邮件。你知道吗file.close
应该是file.close()
,但总的来说,您应该只需要打开一次文件,而不是每次循环都打开一次。打开一次,完成后关闭(假设您将添加一个退出条件)。你知道吗0
(response.json()[0:]
)切片是不必要的。默认情况下,列表从索引0开始。这可能是一个复杂的方式来获得一个新的名单,但这似乎没有必要在这里。你知道吗Coordinates
不应是100None
的硬编码列表。只需使用^{Sighting
。如果你一次又一次地发出请求是没有意义的。如果您想从一个响应遍历pokémon,如果需要索引,请使用^{相关问题 更多 >
编程相关推荐