I am reading a number from a file p2.txt. This file contrains only 1 number which is an integer lets say 10.
test_file = open('p2.txt', 'r')
test_lines = test_file.readlines()
test_file.close()
ferNum= test_lines[0]
print int(ferNum)
when however, I am getting an error
print int(ferNum)
ValueError: invalid literal for int() with base 10: '1.100000000000000000e+01\n'
I can see that it is considering it just as a line. How can I parse that number to a variable? any suggestions? regards
The problem is that even though the value of the number is an integer (11) it is represented in scientific notation so you'd have to read it as a float first.
>>> float('1.100000000000000000e+01\n')
11.0
>>> int('1.100000000000000000e+01\n')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
int('1.100000000000000000e+01\n')
ValueError: invalid literal for int() with base 10: '1.100000000000000000e+01\n'
You can of course convert first to a float then to an int after that.
>>> int(float('1.100000000000000000e+01\n'))
11
Related
I am trying to retrieve one book from a json of books. When retrieving a single book i get this Value Error message on the line that is in bold.
Error -
show_all_books
page_num = int(request.args.get('pn'))
ValueError: invalid literal for int() with base 10: '5df1170a921ee283d8529aa3'
#app.route("/api/v1.0/books", methods=["GET"])
def show_all_books():
page_num, page_size = 1, 10
if request.args.get('pn'):
***page_num = int(request.args.get('pn'))***
if request.args.get('ps'):
page_size = int(request.args.get('ps'))
page_start = (page_size * (page_num - 1))
You are getting this error because you can't convert the string to integer because it have characters that doesn't allow it:
int('5df1170a921ee283d8529aa3')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5df1170a921ee283d8529aa3'
If you try with a number:
int('1231')
1231
So I think that the problem is with the data you receive in get('pn'). The default base of the int() function is 10 but you can do this with hexadecimal base:
int('5df1170a921ee283d8529aa3', 16)
29073565845337865796180941475L
You are getting this error because the string passed to the function can not be represented as an integer.
For instance if you were to do:
int('abc')
you'd get the same error, because the string abc can not be represented as an integer.
The tensorflow, I can't read string,long, only short float allowed? Why?
import tensorflow as tf
import numpy as np
# Data sets
IRIS_TRAINING = "seRelFeatures.csv"
IRIS_TEST = "seRelFeatures.csv"
# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING, target_dtype=np.int)
test_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TEST, target_dtype=np.int)
here is the error
/home/xuejiao/anaconda2/bin/python /home/xuejiao/Desktop/HDSO_DirectAnswer/training_testing/dnn_semiSuper.py
Traceback (most recent call last):
File "/home/xuejiao/Desktop/HDSO_DirectAnswer/training_testing/dnn_semiSuper.py", line 9, in <module>
training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING, target_dtype=np.int)
File "/home/xuejiao/anaconda2/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 47, in load_csv
target[i] = np.asarray(ir.pop(target_column), dtype=target_dtype)
File "/home/xuejiao/anaconda2/lib/python2.7/site-packages/numpy/core/numeric.py", line 482, in asarray
return array(a, dtype, copy=False, order=order)
ValueError: invalid literal for long() with base 10: ''
Process finished with exit code 1
Your error is ValueError: invalid literal for long() with base 10: ''. It simply that you are entering empty string instead of an integer (or string presentation of an integer). I'd check data in CSV files.
Actually I solved this problem by myself, this mistake mean
ValueError: invalid literal for long() with base 10: ''
I have some empty cell, but actually I don't have on the view.
After I check it, it cased by I delete the last column but I just delete the content didn't delete the cells, so from view can't find any empty
I am working on the following python code:
import wave
from bitstring import BitArray
w = wave.open('file.wav','rb')
totalFrames = w.getnframes() #Total number of samples
bytesData = w.readframes(totalFrames)
binData = BitArray(bytesData)
bin2Data = (binData.bin)
The file.wav has 88200 samples at a sampling rate of 44.1KHz.
My goal is to be able to get the 2's compliment of the binary data I obtain from file.wav. 'binData.bin' gives me the binary form of the bytes (\x00\x00N\x00n\xff..) obtained through w.readframes but in a string format.
I was using this to obtain 2'scompliment:
2comp = ~(bin2Data) + 0b1
but in vain. It would show the following error:
Traceback (most recent call last):
File "speaker_bin.py", line 16, in <module>
bin2Data = ~((binData.bin)) + 0b1
TypeError: bad operand type for unary ~: 'str'
I tried int(bin2Data) to convert it but it would not work (It would not print anything at all. I guess because of the size of the data.)
What am I doing wrong?
I would really appreciate any feedback. (even a simple nudge in the right direction)
You need to use
int(binData.bin, 2)
To create an int, you can specify the base as a second parameter, otherwise it will just assume the value is in base 10. As you can see from the docs, the default base is 10, which is why you need to specify a different base other than 10
Also do the same with 0b1
I'm very confused here. I have a code to read a csv file with 2 columns. Here is a piece of data:
1,TF_001_2s
2,TF_002_2s
3,TF_003_2s
4,TF_004_2s
5,TF_005_2s
6,TF_006_2s
7,TF_007_1s
8,TF_008_2s
9,TF_009_2s
10,TF_010_1s
What I want to do is to replace the number of the first column for the name of the second column in a vector. Here is my function:
def rename_flights(self):
index_flight = self.Names.index("Flight ID")
with open('Flight_names.csv','rb') as typical_flights:
typical_flights_read = csv.reader(typical_flights,delimiter=',')
for i in range(len(self.matrix[index_flight])):
flight_id = int(self.matrix[index_flight][i])
for new_typical_flights in typical_flights_read:
if flight_id == int(new_typical_flights[0]):
self.matrix[index_flight][i] = new_typical_flights[1]
This function takes the index of a vector (Names) and uses it in a matrix. This matrix may contain int numbers, and these numbers are those which I want to replace for the string of the csv file. I don't know if I have been enough clear. The problem is in the last line, when I assign the string to the correct position in the matrix. It throws me:
ValueError: could not convert string to float: TF_008_2s
I don't know what could be the fail, because I'm not converting any string to float. I hope you all can help me.
Thanks in advance.
Editing-#1:
Traceback (most recent call last):
File "script_server.py", line 566, in <module>
reading(name)
File "script_server.py", line 552, in reading
info.rename_flights()
File "script_server.py", line 272, in rename_flights
self.results_matrix_rounded[index_flight][i] = new_typical_flights[1]
ValueError: could not convert string to float: TF_008_2s
I am trying to read financial data and store it. The place I get the financial data from stores the data with incredible precision, however I am only interested in 5 figures after the decimal point. Therefore, I have decided to use t = .quantize(cdecimal.Decimal('.00001'), rounding=cdecimal.ROUND_UP) on the Decimal I create, but I keep getting an InvalidOperation exception. Why is this?
>>> import cdecimal
>>> c = cdecimal.getcontext()
>>> c.prec = 5
>>> s = '45.2091000080109'
>>> # s = '0.257585003972054' works!
>>> t = cdecimal.Decimal(s).quantize(cdecimal.Decimal('.00001'), rounding=cdecimal.ROUND_UP)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
cdecimal.InvalidOperation: [<class 'cdecimal.InvalidOperation'>]
Why is there an invalid operation here? If I change the precision to 7 (or greater), it works. If I set s to be '0.257585003972054' instead of the original value, that also works! What is going on?
Thanks!
decimal version gives a better description of the error:
Python 2.7.2+ (default, Feb 16 2012, 18:47:58)
>>> import decimal
>>> s = '45.2091000080109'
>>> decimal.getcontext().prec = 5
>>> decimal.Decimal(s).quantize(decimal.Decimal('.00001'), rounding=decimal.ROUND_UP)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/decimal.py", line 2464, in quantize
'quantize result has too many digits for current context')
File "/usr/lib/python2.7/decimal.py", line 3866, in _raise_error
raise error(explanation)
decimal.InvalidOperation: quantize result has too many digits for current context
>>>
Docs:
Unlike other operations, if the length of the coefficient after the
quantize operation would be greater than precision, then an
InvalidOperation is signaled. This guarantees that, unless there is an
error condition, the quantized exponent is always equal to that of the
right-hand operand.
But i must confess i don't know what this means.