I don't understand why the replace got unresolved attribute reference 'replace' for class 'int' error. And then when the money reach more than 1000, I got value error, even though I tried to handle it with exception by removing comma from the string :
Traceback (most recent call last):
File "C:\Users\DELL\PycharmProjects\Day48_selenium_cookie_clicker\main.py", line 37, in <module>
money = int(cookies_owned.text)
ValueError: invalid literal for int() with base 10: '1,012'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\DELL\PycharmProjects\Day48_selenium_cookie_clicker\main.py", line 50, in <module>
money = int(cookies_owned.text)
ValueError: invalid literal for int() with base 10: '1,012'
This is my code:
from selenium import webdriver
import time
from timeit import default_timer as timer
chrome_driver_path = "C:\Development\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(executable_path=chrome_driver_path)
driver.get("http://orteil.dashnet.org/experiments/cookie/")
timeout = 30 # [seconds]
time_check = time.time() + 5
ids = driver.find_elements_by_xpath('//*[#id]') # find all ids within a webpage
ids_list = [i.get_attribute('id') for i in ids]
items_for_sale_ids = [i for i in ids_list if i[0] == "b" and i[1] == "u" and i[2] == "y"][:8]
items_data = [i.text.split("\n") for i in driver.find_elements_by_id("store")][0]
items_for_sale = [items_data[i].split(" - ") for i in range(len(items_data)) if i % 2 == 0]
price = [int(y[1].replace(",", "")) for y in items_for_sale]
items_pricelist = list(zip(items_for_sale_ids, price))
items_pricelist_dict = {i[1]: i[0] for i in items_pricelist}
start = timer()
cookie = driver.find_element_by_id("cookie")
while True:
cookie.click()
if time.time() > time_check:
# print("hello")
cookies_owned = driver.find_element_by_id("money")
try:
money = int(cookies_owned.text)
affordable_upgrades = {}
for cost, id in items_pricelist_dict.items():
if money > cost:
affordable_upgrades[cost] = id
max_upgrade = max(affordable_upgrades)
print(max_upgrade)
to_purchase_id = affordable_upgrades[max_upgrade]
to_buy = driver.find_element_by_id((to_purchase_id))
to_buy.click()
time_check = time.time() + 5
except ValueError:
money = int(cookies_owned.text)
formatted_money = money.replace(",", "")
affordable_upgrades = {}
for cost, id in items_pricelist_dict.items():
if formatted_money > cost:
affordable_upgrades[cost] = id
max_upgrade = max(affordable_upgrades)
print(max_upgrade)
to_purchase_id = affordable_upgrades[max_upgrade]
to_buy = driver.find_element_by_id((to_purchase_id))
to_buy.click()
time_check = time.time() + 5
see below.
(the problem is the , in value. once we remove it - it works)
value = '1,012'
try:
int_value = int(value)
except ValueError:
print('failed - lets try again..')
int_value = int(value.replace(',',''))
print(int_value)
output
failed - lets try again..
1012
I got value error, even though I tried to handle it with exception by removing comma from the string :
try:
money = int(cookies_owned.text)
...
except ValueError:
money = int(cookies_owned.text)
...
Yes, you handle Exception and after that raise same error again ;)
Correct code is:
try:
money = int(cookies_owned.text)
...
except ValueError:
money = int(cookies_owned.text.replace(",", ""))
...
Or simpler:
try:
money = int(cookies_owned.text.replace(",", ""))
...
except ...
Here is no problem to replace , anytime. You don't need to wait for exception. replace(",", "") will be correct for any number (1, 100, 1,000, 1,000,000, ...)
This won't work: (see comments inserted in the code)
money = int(cookies_owned.text) # money is now an int
formatted_money = money.replace(",", "") # ... but you treat it as a string
Related
I am defining a main_meal_model function to list a lunch plan that takes in a day value. I have previously defined a random_main_meal_dataset function that creates a database of all the foods that are to be eaten at lunch which also takes in the same day value. For some reason i can't omit a forced declaration of the day value in the random_main_meal_dataset function, else it either gives a KeyError or NameError
I have tried every day of the week and it seems perfect as much as my forced declaration is the same as the day value i send when calling the main_meal_model function but as soon as i try to make this an automatic correspondance it sends KeyError: 'Monday' or NameError: name 'day' is not defined per day_data = data[day]
Error messages:
Full Errorr messages:
Traceback (most recent call last):
File "c:\Users\Leonix\Desktop\CS50 Final Project\test.py", line 104, in <module>
print(main_meal_model('Monday', 70, 2000, data, 'Lunch'))
File "c:\Users\Leonix\Desktop\CS50 Final Project\test.py", line 72, in main_meal_model
day_data = data[day]
KeyError: 'Monday
or
Traceback (most recent call last):
File "c:\Users\Leonix\Desktop\CS50 Final Project\test.py", line 103, in <module>
print(main_meal_model('Monday', 70, 2000, data, 'Lunch')) File "c:\Users\Leonix\Desktop\CS50 Final Project\test.py", line 71, in main_meal_model
day_data = data[day] NameError: name 'day' is not defined
Here is the part of the code I suppose is causing the problem
https://pastebin.com/w8XQ8rTn
split_values_day = np.linspace(0, len(data), 8).astype(int)
split_values_day[-1] = split_values_day[-1]-1
def random_main_meal_dataset(data, day):
data = data[data['meal'].str.contains('Main Dishes|Condiments|Side Dishes', na=False)]
frac_data = data.sample(frac=1).reset_index().drop('index', axis=1)
day_data = []
for s in range(len(split_values_day)-1):
day_data.append(
frac_data.loc[split_values_day[s]:split_values_day[s+1]])
return dict(zip(day, day_data))
# define a lunch / dinner model that takes in prob, kg, calories, data and makes a lunch / dinner plan for the day
def main_meal_model(day, kg, calories, data, meal):
data = random_main_meal_dataset(data, day=['Monday'])
G = extract_gram(build_nutritional_values(kg, calories))
E = G['Carbohydrates Grams']
F = G['Fat Grams']
P = G['Protein Grams']
day_data = data[day]
day_data = day_data[day_data.calories != 0]
food = day_data.name.tolist()
c = day_data.calories.tolist()
x = pulp.LpVariable.dicts(
"x", indices=food, lowBound=0, upBound=1.5, cat='Continuous', indexStart=[])
e = day_data.carbohydrate.tolist()
f = day_data.total_fat.tolist()
p = day_data.protein.tolist()
div_meal = meal_split[meal]
prob = pulp.LpProblem("Diet", LpMinimize)
prob += pulp.lpSum([x[food[i]]*c[i] for i in range(len(food))])
prob += pulp.lpSum([x[food[i]]*e[i] for i in range(len(x))]) >= E*0.35
prob += pulp.lpSum([x[food[i]]*f[i] for i in range(len(x))]) >= F*0.35
prob += pulp.lpSum([x[food[i]]*p[i] for i in range(len(x))]) >= P*0.35
prob.solve(PULP_CBC_CMD(msg=0))
variables = []
values = []
for v in prob.variables():
variable = v.name
value = v.varValue
variables.append(variable)
values.append(value)
values = np.array(values).round(2).astype(float)
sol = pd.DataFrame(np.array([food, values]).T,
columns=['Food', 'Quantity'])
sol['Quantity'] = sol.Quantity.astype(float)
sol = sol[sol['Quantity'] != 0.0]
sol.Quantity = sol.Quantity*100
sol = sol.rename(columns={'Quantity': 'Quantity (g)'})
return sol
print(main_meal_model('Monday', 70, 2000, data, 'Lunch'))`
I am trying to get about 10 stock attributes from yahooquery. When some data is not available (e.g. when the company is not making a profit, there is no PE ratio) it raises KeyError. I want to return zero in that case. Is there any way how to simplify my code and not to put Try/Except to every attribute?
def data(ticker): #pulling data about stock from Yahoo Finance API
try:
company_name = Ticker(ticker).quote_type[ticker]["shortName"]
except KeyError:
company_name = 0
try:
stock_price = Ticker(ticker).financial_data[ticker]["currentPrice"]
except KeyError:
stock_price = 0
try:
change = Ticker(ticker).history(interval='1mo', start=(datetime.datetime.today() - datetime.timedelta(days=90)), end=datetime.datetime.today())
change = change["open"]
growth_or_loose = ((change.iloc[-1] / change.iloc[0]) - 1)
except:
growth_or_loose = 0
try:
recommendation = Ticker(ticker).financial_data[ticker]["recommendationKey"]
except KeyError:
recommendation = 0
try:
market_cap = Ticker(ticker).summary_detail[ticker]["marketCap"]
except KeyError:
market_cap = 0
try:
pe = Ticker(ticker).summary_detail[ticker]["trailingPE"]
except KeyError:
pe = 0
try:
pb = Ticker(ticker).key_stats[ticker]["priceToBook"]
except KeyError:
pb = 0
try:
rev_growth = Ticker(ticker).financial_data[ticker]["revenueGrowth"]
except KeyError:
rev_growth = 0
try:
ern_growth = Ticker(ticker).financial_data[ticker]["earningsGrowth"]
except KeyError:
ern_growth = 0
profit_margin = Ticker(ticker).financial_data[ticker]["profitMargins"]
try:
debt2equity = Ticker(ticker).financial_data[ticker]["debtToEquity"]
except KeyError:
debt2equity = 0
data = company_name, stock_price, growth_or_loose, recommendation, market_cap, pe, pb, rev_growth, ern_growth, profit_margin, debt2equity
return list(data)```
In this case you could use the dictionary's get-method instead which would return None instead of KeyError in case the dictionary doesn't contain that key, or if default value (2nd arg) is supplied it would return the default value.
my_dict = {
"hello" : "world"
}
try:
hello = my_dict["NONEXISTING"]
except KeyError:
hello = "greetings"
# the try/except block can be replaced with this, and since the key
# doesn't exist, the method returns "greetings" instead of raising a KeyError
hello = my_dict.get("NONEXISTING", "greetings")
You can also use defaultdict from collections to give a default value to any variable that does not have a value.
First of all convert your dictionary to defaultdict
# Python program to demonstrate
# defaultdict
from collections import defaultdict
# Function to return a default
# values for keys that is not
# present
def def_value():
return "Not Present"
# Defining the dict
d = defaultdict(def_value)
d["a"] = 1
d["b"] = 2
print(d["a"])
print(d["b"])
print(d["c"])
Output:
1
2
Not Present
from yahooquery import Ticker
import time
symbols = {
'AAPL': 'B12','BABA': 'B13','MSFT': 'B14',
}
tickers = Ticker(list(symbols.keys()), asynchronous=True)
try:
while True:
prices = tickers.price
for k, v in symbols.items():
try:
a = str(prices[k]['regularMarketPrice'])
print ("currentPrice : "+a)
except Exception as e:print(0)
try:
b = str(prices[k]['marketCap'])
print ("marketCap : "+b)
except Exception as e:print(0)
try:
c = str(prices[k]['payoutRation'])
print ("payoutRation : "+c)
except Exception as e:print(0)
except Exception as e:
print(e)
time.sleep(2)
except Exception as e:
print(e)
Also you can export this data to excel with:
import xlwings as xw
wb = xw.Book('Filename.xlsx')
sht1 = wb.sheets['Sheet1']
for k, v in symbols.items():
try:
sht1.range(v).value = str(prices[k]['regularMarketPrice'])
v1=v.replace("B", "C")
sht1.range(v1).value = str(prices[k]['regularMarketDayHigh'])
v2=v1.replace("C", "D")
sht1.range(v2).value = str(prices[k]['regularMarketDayLow'])
except Exception as e:
print(e)
I am learning Python and right now I am trying to examine percent change in stock values from a database. However, one of the variables I am trying to examine is coming from a database which is of type Series. And whenever I try to convert into a float to use it for multiplication and division, I receive an error "TypeError: cannot convert the series to ". I have seen solutions that stated to use .astype(float), but that didn't work for me. Any help would be appreciated.
import pandas as pd
import os
import time
from datetime import datetime
path = "C:/Users/andre/AppData/Local/Programs/Python/Python37/SciKit-learn Tutorial/intraQuarter"
def Key_Stats(gather = "Total Debt/Equity (mrq)"):
statspath = path + '/_KeyStats'
stock_list = [x[0] for x in os.walk(statspath)]
counter = 0
df = pd.DataFrame(columns = ['Date','Unix','Folder','DE Ratio','Price',
'Stock_pct_change','SP500','SP500_pct_change', 'Difference'])
sp500_df = pd.read_csv("YAHOO-INDEX_GSPC.csv")
ticker_list = []
for each_dir in stock_list[1:]:
each_file = os.listdir(each_dir)
folder = each_dir.split("\\")[1]
ticker_list.append(folder)
#Reset starting point for each directory
starting_stock_value = False
starting_sp500_value = False
if len(each_file) > 0:
for file in each_file:
date_stamp = datetime.strptime(file, '%Y%m%d%H%M%S.html')
unix_time = time.mktime(date_stamp.timetuple())
full_file_path = each_dir + '/' + file
file_content_source = open(full_file_path, 'r').read()
try:
value = file_content_source.split(gather)[1].split('<td class="yfnc_tabledata1">')[1].split('</td>')[0]
try:
sp500_date = datetime.fromtimestamp(unix_time).strftime('%Y-%m-%d')
row = sp500_df[(sp500_df['Date'] == sp500_date)]
sp500_value = row['Adj Close']
print(type(sp500_value))
print(sp500_value)
except:
sp500_date = datetime.fromtimestamp(unix_time-259200).strftime('%Y-%m-%d')
row = sp500_df[(sp500_df['Date'] == sp500_date)]
sp500_value = row['Adj Close']
try:
stock_price = file_content_source.split('</small><big><b>')[1].split('</b></big>')[0]
if(stock_price.endswith('</span>')):
stock_price = stock_price.split('>')[1].split('</span')[0]
except IndexError:
try:
stock_price = file_content_source.split('</small><big><b>')[1].split('</span>')[0].split('>')[1]
except IndexError:
try:
stock_price = file_content_source.split('<span id="yfs_')
seglist = [] #Created a list to store all the possible numbers that arise
for parts in stock_price:
segment = parts.split('</span>')[0].split('>')[1]
try:
#The numbers are usually 4,5, or 6 characters in length and check if str is a number
if((len(segment) == 4 or len(segment) == 5 or len(segment) == 6) and float(segment) >= 0):
seglist.append(segment) #Add potential number to list
stock_price = seglist[0] #Noticed the first number is usually the correct one
except ValueError:
pass
except IndexError:
print('Error in Folder:', folder, ' File: ', file, ' Stock Price=', stock_price)
#print('Folder:', folder, ' File', file, ' Stock Price: ', stock_price)
if not starting_stock_value:
starting_stock_value = float(stock_price)
if not starting_sp500_value:
starting_sp500_value = float(sp500_value)
#percentage change = (new-old)/old x 100
stock_pct_change = ((float(stock_price) - starting_stock_value) / starting_stock_value) * 100
#-------------------------------------------------------------------------------
#ERROR OCCURS HERE!!!!
sp500_pct_change = ((float(sp500_value) - starting_sp500_value) / starting_sp500_value) * 100
#-------------------------------------------------------------------------------
df = df.append({'Date': date_stamp,'Unix': unix_time,
'Folder': folder,'DE Ratio': value,
'Price': stock_price,
'Stock_pct_change': stock_pct_change,
'SP500': sp500_value,
'SP500_pct_change': sp500_pct_change,
'Difference': stock_pct_change-sp500_pct_change},
ignore_index = True)
except IndexError:
stock_price = file_content_source.split('<span id="yfs_')[5].split('</span>')[0].split('>')[1]
print('Error in Folder:', folder, ' File: ', file, "Value=", value, 'Stock Price=', stock_price)
#Plot
for each_ticker in ticker_list:
try:
plot_df = df[(df['Folder'] == each_ticker)]
plot_df = plot_df.set_index(['Date'])
plot_df['Difference'].plot(label = each_ticker)
plt.legend()
except:
pass
plt.show()
Key_Stats()
Error:
<class 'pandas.core.series.Series'>
2997 1131.130005
Name: Adj Close, dtype: float64
<class 'pandas.core.series.Series'>
2947 1129.439941
Name: Adj Close, dtype: float64
<class 'pandas.core.series.Series'>
2778 1198.680054
Name: Adj Close, dtype: float64
<class 'pandas.core.series.Series'>
Series([], Name: Adj Close, dtype: float64)
Traceback (most recent call last):
File "C:\Users\andre\AppData\Local\Programs\Python\Python37\SciKit-learn Tutorial\Tutorial 6 - Playing with the Data (pct_change).py", line 103, in <module>
Key_Stats()
File "C:\Users\andre\AppData\Local\Programs\Python\Python37\SciKit-learn Tutorial\Tutorial 6 - Playing with the Data (pct_change).py", line 83, in Key_Stats
sp500_pct_change = ((float(sp500_value) - starting_sp500_value) / starting_sp500_value) * 100
File "C:\Users\andre\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\core\series.py", line 93, in wrapper
"{0}".format(str(converter)))
TypeError: cannot convert the series to <class 'float'>
I guess we are working on the same project and on the same path. Here it is. I hope u understand where to insert this portion of the code
try:
sp500_date = datetime.fromtimestamp(unix_time).strftime('%Y-%m-%d')
row = sp500_df[sp500_df["Date"] == sp500_date]
sp500_value = row["Adj Close"]
sp500_value1 = sp500_value.values[0]
print(sp500_value1)
except:
sp500_date = datetime.fromtimestamp(unix_time-259200).strftime('%Y-%m-%d')
row = sp500_df[sp500_df["Date"] == sp500_date]
sp500_value = row["Adj Close"]
sp500_value1 = sp500_value.values[0]
print(sp500_value1)
My scirpt :
if 'recheck' == msg.lower():
with open('Output.txt','r') as rr:
contactArr = rr.readlines()
for v in xrange(len(contactArr) -1,0,-1):
num = re.sub(r'\n', "", contactArr[v])
contacts.append(num)
pass
contacts = list(set(contacts))
for z in range(len(contacts)):
arg = contacts[z].split('|')
if arg[1] == receiver.id :
userList.append(arg[0])
timelist.append(arg[2])
uL = list(set(userList))
# print uL
for ll in range(len(uL)):
try:
getIndexUser = userList.index(uL[ll])
timeSeen.append(strftime("%H:%M:%S", localtime(int(timelist[getIndexUser]) / 1000)))
recheckData.append(userList[getIndexUser])
except IndexError:
conName.append('nones')
pass
contactId = client._getContacts(recheckData)
for v in range(len(recheckData)):
dataResult.append(contactId[v].displayName + '['+timeSeen[v]+']')
pass
# # print len(recheckData)
tukang = "V=ON Members=V\n[*]"
grp = '\n[*] '.join(str(f) for f in dataResult)
receiver.sendMessage("%s %s" % (tukang, grp))
But error in terminal :
Traceback (most recent call last):
File "echobot.py", line 117, in <module>
if arg[1] == receiver.id :
IndexError: list index out of range
Can you help me?
The error is coming from
arg = contacts[z].split('|')
if arg[1] == receiver.id :
userList.append(arg[0])
timelist.append(arg[2])
you should double check that your contacts are all formatted correctly.
According to this code, each contact should be formatted like
user|id|time
If each contact in contacts is not formatted exactly that way, this error will be thrown. It looks like your split('|') fucntion isn't finding any '|' to split on.
I get this error
Traceback (most recent call last):
File "C:\Users\User1\Desktop\cellh5_scripts\ewa_pnas_fate.py", line 90, in <module>
ec.combine_classifiers("Event labels combined")
File "C:\Users\User1\Desktop\cellh5_scripts\ewa_pnas_fate.py", line 53, in combine_classifiers
pnas_class[pnas_class==3] = 1
TypeError: 'numpy.int32' object does not support item assignment
by runing the code
def combine_classifiers(self, output_name):
all_combined_classes = []
for _, (plate_name, w, p, t1, t2, track_ids, track_labels) in self.mapping[['Plate',
'Well',
'Site',
'Gene Symbol',
'siRNA ID',
'Event track ids',
'Event track labels']].iterrows():
combined_classes = []
ch5_file_handle = self.cellh5_handles[plate_name]
ch5_pos = ch5_file_handle.get_position(w, str(p))
for track_id, track_label in zip(track_ids, track_labels):
h2b_class = track_label.copy()
print(track_id)
pnas_class = ch5_pos.get_class_prediction('secondary__expanded')[track_id]['label_idx'] + 1
print(pnas_class)
inter_idx = h2b_class == 1
pnas_class[pnas_class==3] = 1
pnas_class[pnas_class==2]+=2
combined_class = h2b_class
combined_class[inter_idx] = pnas_class[inter_idx]
combined_classes.append(combined_class)
all_combined_classes.append(combined_classes)
self.mapping[output_name] = pandas.Series(all_combined_classes)
I print pnas_class which is 1, and track_id which is 50708. I'm wondering what the designer of code want to do in the part:
inter_idx = h2b_class == 1
pnas_class[pnas_class==3] = 1
pnas_class[pnas_class==2]+=2
combined_class = h2b_class
combined_class[inter_idx] = pnas_class[inter_idx]
How can I change that to have the same meaning?
pnas_class is a an integer so you can't select item from an integer by [pnas_class==3] = 1.
Maybe you are trying to affect 1 to pnas_class if it's equal to 3. In this case try this:
pnas_class= 1*(pnas_class == 3) + pnas_class*(pnas_class != 3 )
Ok I found the mistake. You arer right the pnas_class should not be an integer and I know why is it integer instead of array.