I'm working on a linear regression program and when I try to convert the input file data to a float (it reads in as a string), I get this error. Perhaps someone can help me? I'm using Windows XP, and IDLE. (also the console screen). -
#! /usr/bin/env python
-
import sys
-
import os
-
from numpy import *
-
numLst = [] #an empty list
-
if len(sys.argv) == 2:
-
infile = open(sys.argv[1], 'r')
-
elif len(sys.argv) <2:
-
infile = raw_input("Name of file: ")
-
elif len(sys.argv) > 2:
-
raise SyntaxError, "Too many arguments"
-
data = open(infile, 'r')
-
for x in data:
-
x = float(x) # HERE IS THE PROBLEM
-
numLst.append(x.strip('\n').split(" "))
-
-
a = array(numLst)
-
print a
-
Input file looks like this:
1.0 2.0
2.0 3.5
2.5 5.0
3.5 6.5
which are data points, x and y respectively.
Thanks!
TMS
11 40786 bvdet 2,851
Expert Mod 2GB
I'm working on a linear regression program and when I try to convert the input file data to a float (it reads in as a string), I get this error. Perhaps someone can help me? I'm using Windows XP, and IDLE. (also the console screen). -
#! /usr/bin/env python
-
import sys
-
import os
-
from numpy import *
-
numLst = [] #an empty list
-
if len(sys.argv) == 2:
-
infile = open(sys.argv[1], 'r')
-
elif len(sys.argv) <2:
-
infile = raw_input("Name of file: ")
-
elif len(sys.argv) > 2:
-
raise SyntaxError, "Too many arguments"
-
data = open(infile, 'r')
-
for x in data:
-
x = float(x) # HERE IS THE PROBLEM
-
numLst.append(x.strip('\n').split(" "))
-
-
a = array(numLst)
-
print a
-
Input file looks like this:
1.0 2.0
2.0 3.5
2.5 5.0
3.5 6.5
which are data points, x and y respectively.
Thanks!
TMS
Each iteration reads a line from the file. The argument to float must be in the correct format. See below: - >>> x = '1.0 2.0'
-
>>> float(x)
-
Traceback (most recent call last):
-
File "<interactive input>", line 1, in ?
-
ValueError: invalid literal for float(): 1.0 2.0
-
>>> x,y = [float(i) for i in x.split()]
-
>>> x
-
1.0
-
>>> y
-
2.0
-
>>>
Separate the numbers and pass each one to float().
I'm working on a linear regression program and when I try to convert the input file data to a float (it reads in as a string), I get this error. Perhaps someone can help me? I'm using Windows XP, and IDLE. (also the console screen). -
#! /usr/bin/env python
-
import sys
-
import os
-
from numpy import *
-
numLst = [] #an empty list
-
if len(sys.argv) == 2:
-
infile = open(sys.argv[1], 'r')
-
elif len(sys.argv) <2:
-
infile = raw_input("Name of file: ")
-
elif len(sys.argv) > 2:
-
raise SyntaxError, "Too many arguments"
-
data = open(infile, 'r')
-
for x in data:
-
x = float(x) # HERE IS THE PROBLEM
-
numLst.append(x.strip('\n').split(" "))
-
-
a = array(numLst)
-
print a
-
Input file looks like this:
1.0 2.0
2.0 3.5
2.5 5.0
3.5 6.5
which are data points, x and y respectively.
Thanks!
TMS
Not sure about your error message but if sys.argv == 2 then wouldn't you be opening the file twice? Probably nothing to do with the problem but just thought I'd mention it.
Also, you didn't read the file. Try:
I think that might work.
ok, I see now. But I'm not sure how to use that with my for loop. Or do I use it in the for loop? Shouldn't I convert the file data to float before I append it to my list?
Not sure about your error message but if sys.argv == 2 then wouldn't you be opening the file twice?
Also, you didn't read the file. Try:
I think that might work.
No.
2 = the second argument in the file. Note the 'len' before sys.argv
It reads the file fine. That isn't the problem. I'm trying to convert the data from strings to floats.
No.
2 = the second argument in the file. Note the 'len' before sys.argv
It reads the file fine. That isn't the problem. I'm trying to convert the data from strings to floats.
Oh sorry, but for the file opening I meant -
-
if len(sys.argv) == 2:
-
infile = open(sys.argv[1], 'r')
-
elif len(sys.argv) <2:
-
infile = raw_input("Name of file: ")
-
elif len(sys.argv) > 2:
-
raise SyntaxError, "Too many arguments"
- data = open(infile, 'r')
-
You have two open calls. I'm sorry if I'm being stupid but it doesn't really matter so forget about it.
you aren't being stupid.
My assignment requires that only one file is provided on the command line.
Do you have a better way of doing it?
In tests what I've done works fine. If I provide more than one file I get an error, which is what I want.
Perhaps I'm missing something here. The first arg is 0, second is 1, etc. If the first arg is the program name, the second is the file name I want opened. So, the length of the args should equal 2 or there are two many args, right?
bvdet 2,851
Expert Mod 2GB
ok, I see now. But I'm not sure how to use that with my for loop. Or do I use it in the for loop? Shouldn't I convert the file data to float before I append it to my list?
- >>> numList = []
-
>>> fList = open('data_file').readlines()
-
>>> for x in fList:
-
... numList.append([float(i) for i in x.strip().split()])
-
...
-
>>> numList
-
[[1.0, 2.0], [2.0, 3.5], [2.5, 5.0], [3.5, 6.5]]
-
>>>
If you create a file object, don't forget to close it. Done like above, no file object is created.
you aren't being stupid.
My assignment requires that only one file is provided on the command line.
Do you have a better way of doing it?
In tests what I've done works fine. If I provide more than one file I get an error, which is what I want.
Perhaps I'm missing something here. The first arg is 0, second is 1, etc. If the first arg is the program name, the second is the file name I want opened. So, the length of the args should equal 2 or there are two many args, right?
Ok, sys.argv[1] is the file name. Right? If that's the case then I believe you should get an error message. I tried it: -
>>> infile = open("C:\\testfile.txt", "r")
-
>>> data = open(infile, "r")
-
-
Traceback (most recent call last):
-
File "<pyshell#5>", line 1, in <module>
-
data = open(infile, "r")
-
TypeError: coercing to Unicode: need string or buffer, file found
-
>>>
-
Did it work for you?
Please correct me if I am wrong?
something you might want to take a look -
....
-
if len(sys.argv) == 2:
-
data = open(sys.argv[1], 'r')
-
elif len(sys.argv) <2:
-
infile = raw_input("Name of file: ")
-
data = open(infile, 'r')
-
elif len(sys.argv) > 2:
-
raise SyntaxError, "Too many arguments"
-
for x in data:
-
....
-
sys.argv[0] is the program name, argv[1] is the first argument and so on.
bvdet 2,851
Expert Mod 2GB
ok, I see now. But I'm not sure how to use that with my for loop. Or do I use it in the for loop? Shouldn't I convert the file data to float before I append it to my list?
Here's a one-liner: - >>> [[float(x),float(y)] for x,y in [j.split() for j in open('data.txt').read().split('\n')]]
-
[[1.0, 2.0], [2.0, 3.5], [2.5, 5.0], [3.5, 6.5]]
-
>>>
YEAH!!! thank you. Now I can get down to the complexities of linear regression, which is more busy work than anything. Thank you!
This is what it looks like right now, there are no error messages: -
#! /usr/bin/env python
-
import sys
-
import os
-
from numpy import *
-
numLst = [] #an empty list
-
if len(sys.argv) == 2:
-
infile = open(sys.argv[1], 'r')
-
for x in infile:
-
numLst.append([float(i) for i in x.strip().split()])
-
elif len(sys.argv) <2:
-
infilename = raw_input("Name of file: ")
-
data = open(infilename, 'r')
-
for x in data:
-
numLst.append([float(i) for i in x.strip().split()])
-
elif len(sys.argv) > 2:
-
raise SyntaxError, "Too many arguments"
-
a = array(numLst)
-
print a
-
b = a[0:, 1] #this is just me manipulating the list a bit
-
print b
-
c = a[0:,1]
-
print
-
bA = b[:1]
-
g = bA
-
print numLst
-
-
- >>> numList = []
-
>>> fList = open('data_file').readlines()
-
>>> for x in fList:
-
... numList.append([float(i) for i in x.strip().split()])
-
...
-
>>> numList
-
[[1.0, 2.0], [2.0, 3.5], [2.5, 5.0], [3.5, 6.5]]
-
>>>
If you create a file object, don't forget to close it. Done like above, no file object is created.
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Tim Williams |
last post by:
I'm trying to write a simple python program to access a MySQL
database. I'm having a problem with using MySQLdb to get the results
of a SQL command in a cursor. Sometimes the cursor.execute works,...
|
by: Aki Niimura |
last post by:
Hello everyone,
I started to use pickle to store the latest user settings for the tool
I wrote. It writes out a pickled text file when it terminates and it
restores the settings when it starts....
|
by: Martin MOKREJ© |
last post by:
Hi,
is this a bug or "feature" that I have to use float() to make int() autoconvert
from it?
$ python
Python 2.3.4 (#1, Feb 14 2005, 10:00:27)
on linux2
Type "help", "copyright", "credits"...
|
by: Pedro Miguel Carvalho |
last post by:
Greetings.
I have a class that I would like to initialize with a literal array but it
is not accepted by the compiler. It works if I use a array variable but not
a literal array. Can someone...
|
by: Jon Wilson |
last post by:
How do I write Not A Number or +/- infinity (floating point values) as
literal constants (I'm using g++)?
I have a function that returns float, and I need a flag value, and for
various reasons...
|
by: philip20060308 |
last post by:
Hi all,
Has anyone ever seen Python 2.4.1's httplib choke when reading chunked
content? I'm using it via urrlib2, and I ran into a particular server
that returns something that httplib doesn't...
|
by: abcd |
last post by:
I have the following code which is sent over the wire as a string...
from time import time
class Foo:
def go(self):
print "Time:", time()
I get this code and store it as, "data"
|
by: Eclipse |
last post by:
G'day all
In the code below I am trying to catch an error thrown if i enter any other value than an integer. (I used the string 'six' and the float '1.5')
The error thrown in the command...
|
by: davidj411 |
last post by:
i am parsing a cell phone bill to get a list of all numbers and the
total talktime spend on each number.
i already have a unique list of the phone numbers.
now i must go through the list of...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
| |