问题
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])
回答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)]
And then drawn as lines with turtle.
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:
来源:https://stackoverflow.com/questions/23125581/python-passing-coordinates-from-text-file-to-turtle