【问题标题】:PYTHON 3: Read a file and map the coordinates to the turtle screenPYTHON 3:读取文件并将坐标映射到海龟屏幕
【发布时间】:2015-05-05 01:33:36
【问题描述】:

所以我必须编写一个程序来读取包含地震数据的csv 文件,然后仅从文件中获取纬度和经度并将其映射到 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

【问题讨论】:

    标签: python format turtle-graphics


    【解决方案1】:

    您没有正确使用该文件,让我们将其分解:

    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()
    

    【讨论】:

    • 更新:我的屏幕上什么都没有发生 @DTing
    • 我不明白你的程序。你能用我的程序来做吗? @DTing
    • 请稍候更新。我没注意到你只是在寻找地震。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多