Why does float() fail to convert my string to a float? - python

My program is giving me an error when it tries to convert a string from a list of strings to a floating point number. The list is read from a line in a CSV text file and then separated into a list. How do I make this work and why is it going wrong? Here are the relevant bits of code:
def Main():
srcf = open(bkp, 'r')
for line in srcf:
liLn = line.split(',')
...Then the following function is called...
def Pred_PSME(liLn):
dbh = float(liLn[6])
Here is the line from the file:
1345327,20486,"ABCO","Abies concolor","Y","Y","31.496","0.0779","19.3567",,"0.5602","0",1,"0.9268","11.8968","2.6832","6.6646","2399.256",54.47,24.15,248.47,42.19,9.16,8.16,9.23,272.27,264.11,369.30,345.15,71.80,0.00,0.00,4393.57,4106.22,3239.25,3142.07,854.30,0.00,0.00,,12.70,10.16,15.24,0.02,0.04,0.38,0.38,0.00,0.00,1.95,1.83,1.44,1.40
I get this error message:
Traceback (most recent call last):
File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 263, in <module>
Main()
File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 36, in Main
li_tBQI = BQI_Calc(liLn)
File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 63, in BQI_Calc
di_eqns = {"PSME": Pred_PSME(liLn), "ABAM":Pred_ABAM(liLn), \
File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 172, in Pred_PSME
dbh = float(liLn[6])
ValueError: could not convert string to float: "31.496"
I'm using Python 2.7 on an Ubuntu Linux computer.

You need to strip the double quotes off the string. This will then you give a legitimate floating point string that float() can convert.

Related

Python Error when converting String to Binary

I have a Python script obtained from a project which I am trying to debug however I am unable to resolve one error. Per the author's description of the project, everything works fine.
The script takes a parameter called "ascii" which is of type str as shown below:
parser.add_argument('--ascii', type=str,
help='ASCII Data type: ASCII characters')
Per my understanding, in the following code, it processes the input string one character at a time and each character is sent to a function, iter_bin() which will take the ASCII value of the character and convert it to binary, appending the output to a list.
ASCIIDATA = args.ascii
dataArray = []
for line in ASCIIDATA:
for entry in line:
# Make sure everything is a number, convert if not
dataArray.append(''.join(s for s in iter_bin(entry)))
def iter_bin(s):
sb = s.encode('ascii')
return (format(b, '07b') for b in sb)
When I run this code, I get the following error:
Traceback (most recent call last):
File "check.py", line 107, in <module>
main()
File "check.py", line 70, in main
dataArray.append(''.join(s for s in iter_bin(entry)))
File "check.py", line 70, in <genexpr>
dataArray.append(''.join(s for s in iter_bin(entry)))
File "check.py", line 82, in <genexpr>
return (format(b, '07b') for b in sb)
ValueError: Unknown format code 'b' for object of type 'str'
How can I resolve this error?
Thanks.

Python 2.x to 3.x converted code fails in IO.StringIO conversion

python 2.x code
sdata = StringIO.StringIO(c.data)
python 3.x code
sdata = io.StringIO(c.data)
complete code
def downloadCSV(c, d):
filename = c.getFilename(d)
reqstr = c.getReqStr(d)
print(("Downloading %s ..." % (filename)))
if c.getResponse(reqstr) == -1:
return -1
sdata = io.StringIO(c.data)
z = zipfile.ZipFile(sdata)
Error :
Traceback (most recent call last):
File "xxx.py", line 166, in <module>
main(sys.argv[1:])
File "xxxx.py", line 158, in main
getMonth(c, args[1], args[2])
File "xxxx.py", line 133, in getMonth
if downloadCSV(c, d) > -1:
File "xxxx.py", line 73, in downloadCSV
sdata = io.StringIO(c.data)
TypeError: initial_value must be str or None, not bytes
right import is done for 3.x python version and the conversion for sdata should be automatically happening here ? Why this above error coming ,and what is the way to correct this error in python3.x . Tried other answers posted in this forum but nothing seeming to be working in this case.
Python 3 now makes a difference between str and bytes.
Your request returned binary data, so to be able to store it in a io object you have to create a BytesIO object not a StringIO object. So:
sdata = io.BytesIO(c.data)
Note that the code is still compatible with Python 2.

Python Bag of Words NameError: name 'unicode' is not defined

I have been following this site, https://radimrehurek.com/data_science_python/, to apply bag of words on a list of tweets.
import csv
from textblob import TextBlob
import pandas
messages = pandas.read_csv('C:/Users/Suki/Project/Project12/newData1.csv', sep='\t', quoting=csv.QUOTE_NONE,
names=["label", "message"])
def split_into_tokens(message):
message = unicode(message, encoding="utf8") # convert bytes into proper unicode
return TextBlob(message).words
messages.message.head().apply(split_into_tokens)
print (messages)
However I keep getting this error. I've checked and I following the code on the site but the error keeps arising.
Error
Traceback (most recent call last):
File "C:/Users/Suki/Project/Project12/projectBagofWords.py", line 34, in <module>
messages.message.head().apply(split_into_tokens)
File "C:\Program Files\Python36\lib\site-packages\pandas\core\series.py", line 2510, in apply
mapped = lib.map_infer(values, f, convert=convert_dtype)
File "pandas/_libs/src\inference.pyx", line 1521, in pandas._libs.lib.map_infer
File "C:/Users/Suki/Project/Project12/projectBagofWords.py", line 31, in split_into_tokens
message = unicode(message, encoding="utf8") # convert bytes into proper unicode
NameError: name 'unicode' is not defined
Can someone offer advice on how I could rectify this?
Thanks
unicode is a python 2 method. If you are not sure which version will run this code, you can simply add this at the beginning of your code so it will replace the old unicode with new str:
import sys
if sys.version_info[0] >= 3:
unicode = str
unicode is python 2.x method. If you are running Python 3.x, then all strings are unicode and that call is not needed.
https://docs.python.org/3/howto/unicode.html

Python 3 [TypeError: 'str' object cannot be interpreted as an integer] when working with sockets

I run the script with python3 in the terminal but when I reach a certain point in it, I get the following error:
Traceback (most recent call last):
File "client.py", line 50, in <module>
client()
File "client.py", line 45, in client
s.send(bytes((msg, 'utf-8')))
TypeError: 'str' object cannot be interpreted as an integer
This is the code it refers to.
else :
# user entered a message
msg = sys.stdin.readline()
s.send(bytes((msg, 'utf-8')))
sys.stdout.write(bytes('[Me] '))
sys.stdout.flush()
I read the official documentation for bytes() and another source
https://docs.python.org/3.1/library/functions.html#bytes
http://www.pythoncentral.io/encoding-and-decoding-strings-in-python-3-x/
but I am no closer to understanding how to fix this. I realise that my msg is a string and I need an integer, but I am confused about how to convert it. Can you please help me, or direct me to a source that will help me?
Edit 1: I changed the line
s.send(bytes((msg, 'utf-8')))
to
s.send(bytes(msg, 'utf-8'))
but now I get the following error:
Traceback (most recent call last):
File "client.py", line 50, in <module>
client()
File "client.py", line 46, in client
sys.stdout.write(bytes('[Me] '))
TypeError: string argument without an encoding
Edit 2: According to #falsetru updated answer.
Using bytes literal gives me
TypeError: must be str, not bytes
Change the following line:
s.send(bytes((msg, 'utf-8')))
as:
s.send(bytes(msg, 'utf-8'))
In other words, pass a string and an encoding name instead of a passing a tuple to bytes.
UPDATE accoridng to question change:
You need to pass a string to sys.stdout.write. Simply pass a string literal:
sys.stdout.write('[Me] ')

Python executable cannot read file

Given below is the code that I am using to read values form a file
import linecache
line_number=line_number+1
linecache.getline("write.txt", line_number)
I am using py2exe to convert the file into an executable. The problem is after conversion to exe it cannot read the file.
The error message is:
Could not convert string to a float
As suggested in the comment the full error trace is:
Traceback (most recent call last):
File "logic.py", line 437, in <module>
File "logic.py", line 224, in readdata
ValueError: could not convert string to float:
Where am I going wrong?

Categories