how to convert string to float in for loop in python? - python

I want to calculate the average flow, but I have hard time converting string to float in python.
here is my code in notepad++:
import cookielib,urllib2,urllib,string
import cx_Oracle
import datetime
import string
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
total_flow = 0
count = 0
page = opener.open("http://cdec.water.ca.gov/cgi-progs/queryCSV?station_id=vns&sensor_num=20&dur_code=E&start_date=2016-04-14&end_date=2016-04-15&data_wish=View+CSV+Data")
for line in page:
a=line.split(',')
b = float(a)
count+=1
total_flow= total_flow+b[-1]
# here a=[date,time,flow]; so b[-1] is flow data
ave_flow = total_flow/count
print ave_flow
when I ran this script, I got the error message:
b=float(a)
type error: float() argument must be a string or a number
however, when I directly converted string to float in python, it worked. I don't know what was going on.

Here a is a list not a string. You should have another for loop to handle each element in the list.

a = line.split(',')
This returns a list. That's why you are getting an error.

a=line.split(',')
a is a list here, try something like:
b=float(a[0])

ok, I figured it out. there are some invisible symbol along with string in the list so i can't simply convert string to number.
i changed to
a=line.strip().split(",")
b=float(a[-1])
and it works.

Related

How to pass a currentday() type date/datetime function as a filter to an API in python?

I need to download current day minus 1 data from https://retsapi.raprets.com/CIN/RESO/OData/ every day by passing a filter condition like "&$filter=ModificationTimestamp%20ge%20%272022-03-04T13%3A19%3A56Z%27". Instead of passing timestamp value like I did in the filter condition mentioned I want to pass a date/datetime function. I am using python to make get calls to the API.
How do I make the below code work?
import requests
import json
from datetime import datetime
bearerAccessToken = '#####################'
now = datetime.now()
resourceUrl = "https://retsapi.raprets.com/CIN/RESO/OData/Property?Class=Residential&$filter=ModificationTimestamp{}".format(now)
r = requests.get(resourceUrl, headers={'Authorization' : 'Bearer '+ bearerAccessToken})
print(r.text)
Above code is failing with syntax error:
"error":{ "code":"","message":"An error has occurred.","innererror":{ "message":"Syntax error at position 28 in 'ModificationTimestamp2022-08-01 15:58:03.154348'.","type":"Microsoft.OData.Core.ODataException","stacktrace":"
The correct syntax is "ModificationTimestamp%20ge%20%272022-03-04T13%3A19%3A56Z%27".
How do I convert the output of datetime.now() to match "%20ge%20%272022-03-04T13%3A19%3A56Z%27"?
Assuming you mean you want to pass the output of a date function, you could just use .format() to create the url string and pass the function in there.
def a_date_function():
# code converting string values to appropiate ascii chars
return desired_output
url = "https://retsapi.raprets.com/CIN/RESO/OData/&$filter=ModificationTimestamp{}".format(a_date_function())
api_output = requests.get(url)
And that should give you a full url string with the output from the date function tacked on to the end where the {} is.

How do I replace a JSON list to print to a CSV?

I'm using an API to gather some data that comes to me in JSON format. I'm using json.loads to import the data and can successfully write it to a CSV. Unfortunately, the data comes in in a format that I don't want so I'd like to reformat the json list.
I've tried creating a new list and assigning the JSON list to the desired list. I get the following error: TypeError: list indices must be integers or slices, not str
import requests
import json
import csv
response = requests.get(url).text //json source
data = json.loads(response)
newsdata = (data["response"]["docs"])
// These two lines reformat the date to what I want it to look like
newsdate = [y["pub_date"] for y in newsdata]
newsdate = [y.split('T')[0] for y in newsdate]
newsdata["pub_date"] = newsdate // This line is what I've tried to replace the json
newssnip = [y["snippet"] for y in newsdata]
newshead = [y["headline"]["main"] for y in newsdata]
for z in newsdata:
csvwriter.writerow([z["pub_date"], //This is the JSON data i want to reformat
z["headline"]["main"],
z["snippet"],
z["web_url"]])
I expected the newsdata["pub_date"] to be overwritten when I assigned newsdate to it but I get the following error instead: TypeError: list indices must be integers or slices, not str
Thank you for your help! :)
EDIT:
I've uploaded an example json response here on github called "exmaple.json": https://github.com/theChef613/nytnewsscrapper
That error is saying that newsdata is list and is therefore not subscriptable with a string. If you post the raw JSON data returned or also print(type(newsdata)) to figure out what class newsdata is and how to work with it. It's also possible that newsdata is a 2D (or N-d) array where the first element is the key and the second element is the value.

Is there a way to convert string to list and update a value of list and convert it back to string in one line

What I want to achieve
value = 'a.b.c.d.e'
new_value = value.split('.')
new_value[-1] = F
''.join(new_value)
Now I would like to achieve this in one line. something like below
''.join(value[-1] = F in value.split('.'))
my above expression throws error because it is kind of wrong so is there a possible way to achieve this
Value should be "1.2.3.4.5" and join doesn't work for int. You should use new_value[-1]='10' instead.
''.join(value.split('.')[:-1]+['10'])

Python: Concatenate url with a integer

I'm new in python and I'm trying to concatenate an url with an integer but i get this error:
TypeError: cannot concatenate 'str' and 'int' objects*
My code looks like this:
for x in range(0,10):
url = "http:www.eluniversal.com.mx/minuto-x-minuto?seccion=All&page="+(x)
x +=1
Can someone help me?
Python is a dynamically strongly typed langauge. So it won't convert an integer to string when you try to concatenate them.
You have to either use string interpolation or explicitly convert it to an string.
url = "http:www.eluniversal.com.mx/minuto-x-minuto?seccion=All&page=%s" % x
url = "http:www.eluniversal.com.mx/minuto-x-minuto?seccion=All&page=" + str(x)
url = "http:www.eluniversal.com.mx/minuto-x-minuto?seccion=All&page="+str(x)
Add a "str" in front of your brackets and it will work. By doing this you can convert the int into a string.
url += str(x)
x+=1 has no effect.

Python: 'int' object is not subscriptable

I am getting an error here and I am wondering if any of you can see where I went wrong. I am pretty much a beginner in python and can not see where I went wrong.
temp = int(temp)^2/key
for i in range(0, len(str(temp))):
final = final + chr(int(temp[i]))
"temp" is made up of numbers. "key" is also made of numbers. Any help here?
First, you defined temp as an integer (also, in Python, ^ isn't the "power" symbol. You're probably looking for **):
temp = int(temp)^2/key
But then you treated it as a string:
chr(int(temp[i]))
^^^^^^^
Was there another string named temp? Or are you looking to extract the ith digit, which can be done like so:
str(temp)[i]
final = final + chr(int(temp[i]))
On that line temp is still a number, so use str(temp)[i]
EDIT
>>> temp = 100 #number
>>> str(temp)[0] #convert temp to string and access i-th element
'1'
>>> int(str(temp)[0]) #convert character to int
1
>>> chr(int(str(temp)[0]))
'\x01'
>>>

Categories