Python:将坐标从文本文件传递给海龟 [英] Python: Passing coordinates from text file to Turtle
问题描述
我有一个带有坐标的测试文件,我的目标是创建一个函数,该函数接受文本文件并将其转换为坐标以在海龟中绘制以绘制图像:
I have a test file that has coordinates on it my aim it to create a function that takes the text file and turns it into coordinates to plot in turtle to draw an image:
river, 5
500, 500
-500, 360
400, 500
shadow, 4
500, 300
5, 500
300, 400
到目前为止我有以下内容
so far I have the following
f =open("coordinates.txt", "r")
for line in f:
line=line.split(",")
data=[]
if line:
data.append([i.strip() for i in line])
运行后我得到以下内容:
After running I get the following:
[['river', '5']]
[['500', '500']]
[['-500', 360]]
[['400', '500']]
[['']]
[['shadow', '4']]
[['500', '300']]
[['5', '500']]
[['300', '400']]
[['']]
但是当我通过乌龟时它会坏掉并且不起作用.我的乌龟功能如下:
But when I pass it through turtle it breaks and does not work. My turtle function is as follows:
p=[]
letter=block[0]
for line in block[1:]:
l.append(line)
k=p[0]
turtle.setpos(k[0],k[1])
推荐答案
这似乎是一个随机的代码集合,而不是一个程序.下面是我从数据和代码重建程序的意图.数据按如下方式读入列表:
This seems to be a random collection of code rather than a program. Below is my reconstruction of the intent of the program from the data and code. The data gets read into a list as follows:
[('river', '5'), (500, 500), (-500, 360), (400, 500), ('shadow', '4'), (500, 300), (5, 500), (300, 400)]
然后用乌龟画成线.
import turtle
turtle.setup(1000, 1000)
data = []
with open('coordinates.txt') as my_file:
for line in my_file:
line = line.rstrip()
if line:
x, y = line.split(', ', maxsplit=1)
try:
data.append((int(x), int(y)))
except ValueError:
data.append((x, y))
print(data)
turtle.penup()
for pair in data:
if isinstance(pair[0], int):
turtle.setpos(pair)
turtle.pendown()
else:
print('Drawing {} ({})'.format(*pair))
turtle.penup()
turtle.hideturtle()
turtle.done()
我不能说示例图很有趣:
I can't say the example drawing is at all interesting:
这篇关于Python:将坐标从文本文件传递给海龟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!