简体   繁体   English

使用Python龟从csv文件中使用坐标绘制地图

[英]Plotting map with coordinate from a csv file using Python turtle

Ι am trying to plot a map from a csv file using turtle graphic. 我试图使用龟图形从csv文件绘制地图。

My csv file is here: http://textuploader.com/5nau2 我的csv文件在这里: http : //textuploader.com/5nau2

My program: 我的节目:

import turtle
import csv
import math

def drawMap():
    filename = "C:\python-exercises\coordinates1.csv"

    trace = turtle.Turtle()
    trace.up()

    #scr = Screen()

    with open(filename, 'r') as csvfile:
        reader = reader = csv.DictReader(csvfile)
        for row in reader:

            x = (row[0])
            y = (row[1])
            trace.goto(x,y)
            trace.write(".")
    raw_input()
    #scr.mainloop()
drawMap()

But it is not displaying anything, and also generates errors like: 但是它没有显示任何内容,并且还会生成如下错误:

x = row([0])

keyError: 0

The following should get you started. 以下内容将帮助您入门。 The file you are trying to read in is not in csv format, so instead of using the csv library you could read the rows in yourself as follows: 您尝试读入的文件不是csv格式,因此您可以按如下方式读取自己的行,而不是使用csv库。

import turtle
import math

def drawMap():
    filename = r"C:\python-exercises\coordinates1.csv"

    trace = turtle.Turtle()
    trace.up()

    #scr = Screen()

    with open(filename, 'r') as f_input:
        for row in f_input:
            row = row.strip('()\n').split(',')
            x = float(row[0])
            y = float(row[1])
            trace.goto(x,y)
            trace.write(".")
    raw_input()
    #scr.mainloop()
drawMap()

This takes each row, removes the outer parenthesis and newline and splits it into two columns. 这将占用每一行,删除外部括号和换行符,并将其分为两列。 The columns are then converted to floats for your turtle program to interpret. 然后将列转换为floats以便您的乌龟程序进行解释。

If you are ever not sure about why something is not working, add some print statements to see what is happening. 如果您不确定某些内容无效的原因,请添加一些print语句以查看发生的情况。

Also, do not forget to prefix your filename path with r , this stops Python from trying to interpret the backslashes in your string. 另外,不要忘记在文件名路径前加上r ,这会阻止Python尝试解释字符串中的反斜杠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM