2015-05-05 64 views
0

因此,我必須編寫一個程序,該程序讀取包含地震數據的csv文件,然後僅從文件中獲取緯度和經度,並將其映射到在Python龜屏幕3.PYTHON 3:讀取文件並將座標映射到烏龜屏幕

這是CSV file

我的程序:

import turtle 
def drawQuakes(): 
filename = input("Please enter the quake file: ") 
readfile = open(filename, "r") 
readlines = readfile.read() 

start = readlines.find("type") 
g = readlines[start] 
Type = g.split(",") 
tracy = turtle.Turtle() 
tracy.up() 
for points in Type: 
    print(points) 
    x = float(Type[1]) 
    y = float(Type[2]) 
    tracy.goto(x,y) 
    tracy.write(".") 
drawQuakes() 

我知道這個節目是相當容易的,但我不斷收到此錯誤:

x = float(Type[1])IndexError: list index out of range 

回答

0

你沒有正確使用的文件,讓我們來分析一下:

readlines = readfile.read() 
# readlines is now the entire file contents 

start = readlines.find("type") 
# start is now 80 

g = readlines[start] 
# g is now 't' 

Type = g.split(",") 
# Type is now ['t'] 

tracy = turtle.Turtle() 
tracy.up() 
for points in Type: 
    print(points) 
    # points is 't' 

    x = float(Type[1]) 
    # IndexError: list index out of range 

    y = float(Type[2]) 
    tracy.goto(x,y) 
    tracy.write(".") 

我會用csv.DictReader:

import turtle 
import csv 

def drawQuakes(): 
    filename = input("Please enter the quake file: ") 

    tracy = turtle.Turtle() 
    tracy.up() 

    with open(filename, 'r') as csvfile: 
     reader = reader = csv.DictReader(csvfile) 
     for row in reader: 
      if row['type'] == 'earthquake': 
       x = float(row['latitude']) 
       y = float(row['longitude']) 
       tracy.goto(x,y) 
       tracy.write(".") 

drawQuakes() 

enter image description here

+0

UPDATE:**沒事發生在我的屏幕** @DTing –

+0

我不明白你的程序。你能用我的程序嗎? @DTing –

+0

給我一分鐘更新。我沒有注意到你只是在尋找地震。 – DTing