开发者

python array error

hello I am trying to load coordinates for plotting from a text file and I keep getting an error I don't understand. The coordinates look like this in the file (0.1, 0.0, 0.0), (0.613125, 0.52202, 0.19919) Here is the code I am trying to run:

from visual import *

with open ('/Desktop/Coordlist2.txt','r') as open_file:

    rightFace = curve(pos=[(1,-1,-1), (1,-1,1), (1,-1,-1),(1,1,-1),(1,1,-1),(1,1,1),(1,1,1),(1,-1,1)], radius=0.01, color=color.cyan)
    backFace = curve(pos=[(1,-1,-1), (-1,-1,-1), (-1,-1,-1),(-1,1,-1),(-1,1,-1),(1,1,-1)], radius=0.01, color=color.cyan)
    leftFace = curve(pos=[(-1,-1,-1), (-1,-1,1), (-1,-1,1),(-1,1,1),(-1,1,1),(-1,1,-1)], radius=0.01, color=color.cyan)
    frontFace = c开发者_如何学JAVAurve(pos=[(-1,-1,1), (1,-1,1), (1,1,1),(-1,1,1)], radius=0.01, color=color.cyan)

    for line in open_file.readlines():
        coords = line
        points(pos=[coords], size=1, color=color.yellow)

This is the error message I am getting:

Traceback (most recent call last):
  File "/Users/Graphs.py", line 15, in <module>
    points(pos=[coords], size=1, color=color.yellow)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vis/primitives.py", line 84, in __init__
    self.process_init_args_from_keyword_dictionary( keywords )
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vis/primitives.py", line 212, in process_init_args_from_keyword_dictionary
    setattr(self, key, value)
ValueError: Object cannot be converted to array.

Any help would be greatly appreciated


How they look in the file is irrelevant; they're read as strings. You'll need to parse the lines before they can be used; try ast.literal_eval().


The problem is here:

for line in open_file.readlines():
    coords = line

When you read a line from a file, you always get a string. You then have to process that string to produce whatever data structure you need. So if you have a line that looks like this (for example)

l = '(5, 6, 7)'

you have to explicitly break it up and create a tuple from it:

l_tuple = tuple(int(n) for n in l.strip('()').split(','))

Also, as agf reminded me, you should probably just do for line in open_file; open_file.readlines creates a copy of the file in memory, while for line in open_file just iterates over the lines individually, without copying the entire file into memory.

Just to be as complete as possible, to convert a string that looks like this:

s = '(0.1, 0.0, 0.0), (0.613125, 0.52202, 0.19919)'

You can do this:

>>> numbers = tuple(float(n.strip('( )')) for n in s.split(','))
>>> t1, t2 = numbers[:3], numbers[3:]

This works as long as there are always two tuples of 3 per line.

agf's solution in his comment works too, but it's a bit more brittle, since the tuples must be separated by '), (' exactly. To tell the truth, Ignacio's solution is really the best. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜