I inherited a bit of Python code and I have no background. I am getting unbound local error and is probably something really silly on my part.
UnboundLocalError Traceback (most recent call last)
Input In [1], in <cell line: 372>()
368 print('\n----------------------------------------------------------------------\n')
369 ##############################################################################
--> 372 main()
Input In [1], in main()
319 Gender = p.getGender()
320 StateRes = p.getStateRes()
--> 321 children = immunte(Fname, Lname, DOB, Gender, driver)
323 if children == []:
324 not_found += 1
Input In [1], in immunte(Fname, Lname, DOB, Gender, driver)
204 except WebDriverException:
205 al = []
--> 207 return al
UnboundLocalError: local variable 'al' referenced before assignment
I have looked at this for a few days now and I can't seem to find an answer to this problem even though it is likely simple. It seems a solution to this error is a global keyword somewhere but I am not sure if this applies here as every time I tried to apply global to al = [] i got an error or same result. Any help is appreciated, thank you.
# Imports
import csv
import datetime
import os
import os.path
import time
import pandas as pd
from dateutil.parser import parse
from pandas import DataFrame
from selenium import webdriver
from selenium.common.exceptions import (NoSuchElementException,
WebDriverException)
from selenium.webdriver.support.select import Select
from selenium.webdriver.chrome.service import Service
##############################################################################
# Classes
class Person(object):
def __init__(self, measYr, MEMID, MIDSK, fname, lname, LNMSFX, DRB, GDR, STRES, meas):
self.measYr = measYr
self.MEMID = MEMID
self.MIDSK = MIDSK
self.fname = fname
self.lname = lname
self.LNMSFX = LNMSFX
self.DRB = DRB
self.GDR = GDR
self.STRES = STRES
self.meas = meas
def GTMESYR(self):
return self.measYr
def GTMEMSKY(self):
return self.MIDSK
def GTMEMID(self):
return self.MEMID
def GTFSNM(self):
return self.fname
def GTLSNM(self):
return self.lname
def GTLSTNMSF(self):
return self.LNMSFX
def GTDRB(self):
return self.DRB
def GTGDR(self):
return self.GDR
def getStateRes(self):
return self.STRES
def getMeas(self):
return self.meas
###############################################################################
# Function
def is_date(string, fuzzy=False):
try:
parse(string, fuzzy=fuzzy)
return True
except ValueError:
return False
def immunte(Fname, Lname, DRB, GDR, driver):
# work on search button
driver.find_element_by_xpath("//*[#id='edittesttest']").click()
# work on
lastname = driver.find_element_by_id("LM")
lastname.clear()
lastname.send_keys(Lname)
# work on
firstname = driver.find_element_by_id("FN")
firstname.clear()
firstname.send_keys(Fname)
# work on
birthdate = driver.find_element_by_id("DRB")
birthdate.clear()
birthdate.send_keys(DRB)
# work on advanced search button to input GDR
try:
driver.find_element_by_xpath(
"//*[#id='queryResultsForm']/table/tbody/tr/td[2]/table/tbody/tr[3]/td/table/tbody/tr[2]/td[5]/input").click()
# work on GDR selection button
obj = Select(driver.find_element_by_name("OSC"))
if GDR == 'W':
obj.select_by_index(2)
elif GDR == 'S':
obj.select_by_index(1)
else:
obj.select_by_index(3)
# work on search button
driver.find_element_by_name("cmdFindClient").click()
# two scenarios could emerge as a search result: 1, not found 2, the found
if "No were found for the requested search criteria" in driver.find_element_by_id("queryResultsForm").text:
al = []
elif "the found" in driver.find_element_by_id("queryResultsForm").text:
# work on button
driver.find_element_by_xpath(
"//*[#id='queryResultsForm']/table[2]/tbody/tr[2]/td[2]/span/label").click()
# work on pt button
driver.find_element_by_id("redirect1").click()
# work on getting rid of opt out - header
header = driver.find_elements_by_class_name("large")[1].text
if "Access Restricted" in header:
print(Fname+' '+Lname+' '+" Opt out")
al = []
elif "Information" in header:
# find the first line
first = driver.find_element_by_xpath(
"//*[#id='container']/table[3]/tbody/tr/td[2]/table[2]/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr[5]/td[1]").text
if (first == None):
al = []
else:
even = driver.find_elements_by_class_name("evenRow")
odd = driver.find_elements_by_class_name("oddRow")
o = []
e = []
for value in odd:
o.append(value.text)
for value in even:
e.append(value.text)
length = len(o)
i = 0
al = []
# merge odd and even row together and remove the row marked with complete
while i < length:
al.append(e[i])
al.append(o[i])
i = i+1
# parse each row of information with a comma, add group name for row that are without one
for x in range(len(al)):
if is_date(al[x][1:10]):
al[x] = al[x].replace(' ', ',')
al[x] = al[x].replace(',of,', ' of ')
al[x] = group + ',' + al[x][2:]
else:
al[x] = al[x].replace(' ', ',')
al[x] = al[x].replace(',of,', ' of ')
g = al[x].split(',', 1)
group = g[0]
# work on returning to home page
driver.find_element_by_xpath(
"//*[#id='headerMenu']/table/tbody/tr/td[2]/div/a").click()
except NoSuchElementException:
al = []
except WebDriverException:
al = []
return al
def main():
# Welcome message and input info
print('\nThis is the test.')
print('You will be prompted to type .')
print('If you need to exit the script and stop its process press \'CTRL\' + \'C\'.')
file = input("\nEnter file name: ")
user = input("\nEnter username: ")
pw = input("\nEnter password: ")
date = str(datetime.date.today())
# output file
fileOutputName = 'FILELIST' + \
date.replace('-', '_') + '.csv'
fileOutputNameNotFound = 'NOTFOUNDFILELIST' + \
date.replace('-', '_') + '.csv'
fileOutput = open(fileOutputName, 'w')
fileOutputNotFound = open(fileOutputNameNotFound, 'w')
fileOutput.write('MEAS_YR,MEMLFIDSK,MEMLFID,MEMB_FRST_NM,MEMLSTNM,' +
'DRB,GNDR,RSDNC_STATE,IMUN_RGSTRY_STATE,VCCN_GRP,VCCN_ADMN_DT,DOSE_SERIES,' +
'BRND_NM,DOSE_SIZE,RCTN\n')
fileOutputNotFound.write('MEAS_YR,MEMLFIDSK,MEMLFID,MEMB_FRST_NM,MEMLSTNM,MEMB_SUFFIX,' +
'DRB,GNDR,RSDNC_STATE,IMUN_RGSTRY_STATE,VCCN_GRP,VCCN_ADMN_DT,DOSE_SERIES,' +
'BRND_NM,DOSE_SIZE,RCTN\n')
# If the file exists
try:
os.path.isfile(file)
except:
print('File Not Found\n')
df = pd.read_excel(file)
# create array of People objects and member ID
peopleArray = []
memberIdArray = []
df.dropna()
total = len(df)
not_found = 0
found = 0
# assign each record in the data frame into Person class
for i in range(total):
measYr = str(df.loc[i, "MEAS_YR"])
MEMID = str(df.loc[i, "MEMLFID"])
MIDSK = str(df.loc[i, "MEMLFIDSK"])
fname = str(df.loc[i, "MEMLFID"])
lname = str(df.loc[i, "MEMLSTNM"])
inputDate = str(df.loc[i, "DRB"])
# If date is null then assign an impossible date
if not inputDate:
DRB = '01/01/1900'
if '-' in inputDate:
DRB = datetime.datetime.strptime(
inputDate, "%Y-%m-%d %H:%M:%S").strftime('%m/%d/%Y')
else:
DRB = datetime.datetime.strptime(
str(df.loc[i, "DRB"]), '%m/%d/%Y').strftime('%m/%d/%Y')
GDR = str(df.loc[i, "GDR"])
STRES = str(df.loc[i, "STATE_RES"])
meas = str(df.loc[i, "MEAS"])
p = Person(measYr, MEMID, MIDSK, fname, lname,
LNMSFX, DRB, GDR, STRES, meas)
# append array
m = df.loc[i, "MEMLFID"]
if (m not in memberIdArray):
peopleArray.append(p)
memberIdArray.append(m)
# work on setting up driver for md immunet - mac forward slash/windows double backward slash
PATH = os.getcwd()+'\\'+'chromedriver'
s = Service(PATH)
driver = webdriver.Chrome(service = s)
driver.get("https://www.wow2.pe.org/prd-IR/portalmanager.do")
# work on login ID
username = driver.find_element_by_id("userField")
username.clear()
username.send_keys(user)
# work on password
password = driver.find_element_by_name("password")
password.clear()
password.send_keys(pw)
# work on getting to home page - where loop will start
driver.find_element_by_xpath(
"//*[#id='loginButtonForm']/div/div/table/tbody/tr[3]/td[1]/input").click()
for n in range(total):
p = peopleArray[n]
recordToWrite = ''
print('Looking up: ' + str(n)+' ' +
p.GTLSNM() + ', ' + p.GTFSNM())
MeasYr = p.GTMESYR()
MIDSK = p.GTMEMSKY()
MEMID = p.GTMEMID()
Fname = p.GTFSNM()
Lname = p.GTLSNM()
DRB = str(p.GTDRB())
GDR = p.GTGDR()
STRES = p.getStateRes()
children = immunte(Fname, Lname, DRB, GDR, driver)
if children == []:
not_found += 1
recordToWrite = MeasYr+','+MIDSK+','+MEMID+',' + Fname + \
','+Lname + ',' + ' ' + ','+DRB+','+GDR+','+STRES+','+'MD'
fileOutputNotFound.write(recordToWrite + '\n')
elif children != []:
found += 1
for x in range(len(children)):
data_element = children[x].split(",")
# if the admin date is not valid
if is_date(data_element[1]) and is_date(data_element[3]):
children[x] = ''
elif is_date(data_element[1]) and data_element[2] == 'NOT' and data_element[3] == 'VALID':
children[x] = ''
elif is_date(data_element[1]) and is_date(data_element[3]) == False:
if data_element[5] != 'No':
data_element[4] = data_element[5]
data_element[5] = ''
children[x] = ','.join(data_element[0:6])
else:
data_element[5] = ''
children[x] = ','.join(data_element[0:6])
else:
children[x] = ''
for x in range(len(children)):
if children[x] != '':
recordToWrite = MeasYr+','+MIDSK+','+MEMID+',' + \
Fname+','+Lname + ','+DRB+','+GDR+','+STRES+','+'MD'
recordToWrite = recordToWrite+','+children[x]
fileOutput.write(recordToWrite + '\n')
n = +1
fileOutput.close()
fileOutputNotFound.close()
print('\n--------------------------------OUTPUT--------------------------------')
print("Script completed.")
##############################################################################
main()
You can try this in the 'immunte' function:
def immunte(Fname, Lname, DRB, GDR, driver):
al = []
# work on search button
driver.find_element_by_xpath("//*[#id='edittesttest']").click()
# work on
lastname = driver.find_element_by_id("LM")
lastname.clear()
lastname.send_keys(Lname)
# work on
firstname = driver.find_element_by_id("FN")
firstname.clear()
firstname.send_keys(Fname)
# work on
birthdate = driver.find_element_by_id("DRB")
birthdate.clear()
birthdate.send_keys(DRB)
# work on advanced search button to input GDR
try:
driver.find_element_by_xpath(
"//*[#id='queryResultsForm']/table/tbody/tr/td[2]/table/tbody/tr[3]/td/table/tbody/tr[2]/td[5]/input").click()
# work on GDR selection button
obj = Select(driver.find_element_by_name("OSC"))
if GDR == 'W':
obj.select_by_index(2)
elif GDR == 'S':
obj.select_by_index(1)
else:
obj.select_by_index(3)
# work on search button
driver.find_element_by_name("cmdFindClient").click()
# two scenarios could emerge as a search result: 1, not found 2, the found
if "No were found for the requested search criteria" in driver.find_element_by_id("queryResultsForm").text:
return al
if "the found" in driver.find_element_by_id("queryResultsForm").text:
# work on button
driver.find_element_by_xpath(
"//*[#id='queryResultsForm']/table[2]/tbody/tr[2]/td[2]/span/label").click()
# work on pt button
driver.find_element_by_id("redirect1").click()
# work on getting rid of opt out - header
header = driver.find_elements_by_class_name("large")[1].text
if "Access Restricted" in header:
print(Fname+' '+Lname+' '+" Opt out")
return al
if "Information" in header:
# find the first line
first = driver.find_element_by_xpath(
"//*[#id='container']/table[3]/tbody/tr/td[2]/table[2]/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr[5]/td[1]"
).text
if (first == None):
return al
even = driver.find_elements_by_class_name("evenRow")
odd = driver.find_elements_by_class_name("oddRow")
o = []
e = []
for value in odd:
o.append(value.text)
for value in even:
e.append(value.text)
length = len(o)
i = 0
al = []
# merge odd and even row together and remove the row marked with complete
while i < length:
al.append(e[i])
al.append(o[i])
i = i+1
# parse each row of information with a comma, add group name for row that are without one
for x in range(len(al)):
if is_date(al[x][1:10]):
al[x] = al[x].replace(' ', ',')
al[x] = al[x].replace(',of,', ' of ')
al[x] = group + ',' + al[x][2:]
else:
al[x] = al[x].replace(' ', ',')
al[x] = al[x].replace(',of,', ' of ')
g = al[x].split(',', 1)
group = g[0]
# work on returning to home page
driver.find_element_by_xpath(
"//*[#id='headerMenu']/table/tbody/tr/td[2]/div/a").click()
except NoSuchElementException:
pass
except WebDriverException:
pass
return al
Code :
import requests
from bs4 import BeautifulSoup
import tweepy
import apikey
def work():
auth = tweepy.OAuthHandler(apikey.API_KEY, apikey.API_SECRET_KEY)
auth.set_access_token(apikey.ACCESS_TOKEN, apikey.ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
try:
api.verify_credentials()
print("Authentication OK")
except:
print("Error during authentication")
score_check = 0
init = 0
url = "https://www.espncricinfo.com/live-cricket-score"
r = requests.get(url)
htmlContent = r.content
soup = BeautifulSoup(htmlContent, 'html.parser')
live_check = soup.find_all("div", class_="match-info match-info-FIXTURES")
api.update_status('----Live Scores----')
for i in live_check:
statusRed = 0
for ik in i.children:
if ik['class'] == ['status', 'red'] and ik.get_text() == 'live':
statusRed += 1
if statusRed == 1:
teams_parent = i.find("div", class_="teams")
score = []
team_names = []
i=0
check_one = ''
check_two = ''
flag_one = 0
flag_two = 0
teams = teams_parent.find_all("div", class_="team")
for team in teams:
score_info = team.find("div", class_="score-detail")
if score_info and i == 0:
score.append(score_info.get_text())
check_one = 'Printed A Score'
flag_one = 1
elif i == 0 and flag_one == 0 :
check_one = 'Did Not Print A Score'
if score_info and i == 1:
score.append(score_info.get_text())
check_two = 'Printed B Score'
flag_two = 1
elif i == 0 and flag_two == 0 :
check_two = 'Did Not Print B Score'
team_Detail = team.find("div", class_="name-detail")
if team_Detail:
team_names.append(team_Detail.get_text())
i+=1
#print(check_one)
#print(check_two)
if len(team_names) == 2 and len(score) == 2:
api.update_status(team_names[0], score[0], 'Vs', team_names[1], score[1])
elif len(team_names) == 2 and check_one == 'Printed A Score':
api.update_status(team_names[0], score[0], 'Vs', team_names[1])
elif len(team_names) == 2 and check_two == 'Printed B Score':
api.update_status(team_names[0], 'Vs', team_names[1], score[0])
else:
print('Multiple teams Found For A Match')
if(score[0] == score[0] + 2 or score[1] == score[1] + 2):
init = init + 2
while(1):
work()
**Problems :
Image of the errors:
It is working correctly in python. However when I go to tweet it , it displays these errors...But when I simply print Live Scores, it works.
Please help me out with this.
import requests
from bs4 import BeautifulSoup
import tweepy
import apikey
#Connects to twitter, check the credentials and returns the api
def connect_to_twitter():
auth = tweepy.OAuthHandler(apikey.API_KEY, apikey.API_SECRET_KEY)
auth.set_access_token(apikey.ACCESS_TOKEN,apikey.ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
try:
api.verify_credentials()
print("Authentication OK")
except:
print("Error during authentication")
finally:
return api
#Post To Twitter refer to last line of code.
#Add a forloop to post muliple games.
def post_to_twitter(game):
API = connect_to_twitter()
return API.update_status(game.get("team_1")+": "+game.get("team_1_score")+" VS "+game.get("team_2")+": "+game.get("team_2_score"))
def scraper():
games_list = []
status = ''
url = "https://www.espncricinfo.com/live-cricket-score"
r = requests.get(url)
htmlContent = r.content
soup = BeautifulSoup(htmlContent, 'html.parser')
games = soup.find_all("div", class_="match-info match-info-FIXTURES")
for game in games:
score_info = []
team_info = []
teams = game.find("div", class_="teams")
try:
get_status = game.find("div", class_="status red")
status = get_status.text
except AttributeError:
status = "status error"
continue
for team in teams:
raw_team = team.find("div", class_="name-detail").text
team_info.append(raw_team)
try:
raw_score = team.find("div", class_="score-detail").text
score_info.append(raw_score)
except AttributeError:
score_info.append('0')
game_dict = {
"team_1": team_info[0],
"team_1_score": score_info[0],
"team_2": team_info[1],
"team_2_score": score_info[1],
"status": status
}
games_list.append(game_dict)
return games_list
post_to_twitter(game=scraper()[0])
For you to solve my problem I think you have to run it on your own. My problem is in this line print(Customer_Name, "has spent", Customers[Customer_Name]['TotalAmount'], "in total")
For you to understand better. For example here, It says Michael has spent 60.0 in total when it should be Michael has spent 20.0 in total
import datetime
import uuid # GET A RANDOM ID FOR THE CUSTOMER
from csv import DictWriter
from datetime import date # GET CURRENT DATE AND TOMORROW DATE
import os
def openFile(): # STARTS HERE
try:
os.startfile('data_entered.csv')
except Exception as e:
print(str(e))
# OPEN FILE WHEN USER(EMPLOYEE) WANTS TO
def closeFile():
try:
os.system('TASKKILL /F /IM notepad.exe')
except Exception as e:
print(str(e)) # ENDS HERE
file = open('CustomerNames.txt', 'a')
file1 = open('Orders_Per_Users.txt', 'a')
file2 = open('data_entered.csv', 'a')
ORDERS_FROM_EMPLOYEE = 0
x = -1
length = 0
Total_Amount = 0.0
Customer_List = []
Address_List = []
My_List = []
today = datetime.date.today()
Today_Key = date.toordinal(date.today())
Today_Date = date.today()
Tomorrow_Date = datetime.date.today() + datetime.timedelta(days=1)
Customers = {}
Dates = {}
print("Welcome to our coffee shop!")
print("Login")
# EMPLOYEE LOGIN PROCESS STARTS
UserLogin = {"Employee1": "coffeeshop1", "Employee2": "coffeeshop2", "Employee3": "coffeeshop3"}
username = password = ''
while True:
username = input("Username: ")
password = input("Password: ")
if (username in UserLogin) and (UserLogin[username] == password):
print("Login Successful")
break
else:
print("Invalid Login. Try again")
# EMPLOYEE LOGIN PROCESS ENDS
# PROCESS AFTER ORDER PLACEMENT STARTS
print("Current Date is: {}".format(Today_Date))
process1 = True
process2 = True
while process1:
while process2:
x += 1
Customer_Name = input("Customer's Name:")
Customer_Address = input("Customer's Address:")
if Customer_Name in Customer_List and Customer_Address in Address_List:
First_Index = Customer_List.index(Customer_Name)
Second_Index = Address_List.index(Customer_Address)
if Customer_Name == Customer_List[First_Index]:
Customer_List.pop(First_Index)
x -= 1
Address_List.append(Customer_Address)
Customer_List.append(Customer_Name)
if Today_Key not in Dates:
Dates[Today_Key] = {}
if Customer_Name not in Dates[Today_Key]:
Dates[Today_Key][Customer_Name] = 1
else:
Dates[Today_Key][Customer_Name] += 1
if Customer_Name in Customers:
Customers[Customer_Name]['Orders'] += 1
Customers[Customer_Name]['TotalAmount'] = Total_Amount
else:
Customers[Customer_Name] = {}
Customers[Customer_Name]['Name'] = Customer_Name
Customers[Customer_Name]['Address'] = Customer_Address
Customers[Customer_Name]['ID'] = uuid.uuid1()
Customers[Customer_Name]['Orders'] = 1
Customers[Customer_Name]['TotalAmount'] = 0
Order_Price = float(input("Total amount of order:"))
ORDERS_FROM_EMPLOYEE += 1
print(Customer_Name, "has ordered {} time(s)".format(Customers[Customer_Name]['Orders']))
Total_Amount = Order_Price + Total_Amount
if Tomorrow_Date == Today_Date: # WHEN THIS IS TRUE, IT MEANS THAT THE DATE CHANGED
print("Total amount of orders today is:{} ".format(Total_Amount)) # NUMBER OF ORDERS IN ONE SPECIFIC DAY
answer1 = input("Send another order? (Y/N)").lower()
if Customers[Customer_Name]['Orders'] == 1:
print("This is the first time", Customer_Name, "orders")
Customers[Customer_Name]['TotalAmount'] = Order_Price
else: # TOTAL AMOUNT OF ALL ORDERS DELIVERED
print(Customer_Name, "has spent", Customers[Customer_Name]['TotalAmount'], "in total")
process2 = answer1 == "y"
LengthCustomersList = len(Customer_List)
length += 1
if int(length) == int(LengthCustomersList):
process1 = False
file1.write(username + " has placed {} orders today".format(ORDERS_FROM_EMPLOYEE))
for i in Customer_List:
file.write(i + '\n')
csv_writer = DictWriter(open('data_entered.csv', 'a'),
fieldnames=['Customer Name', 'Customer Address', 'Customer ID', 'Total Orders',
'Total Amount'])
csv_writer.writeheader()
for customer_name in Customers.keys():
csv_writer.writerows(
[{'Customer Name': Customers[customer_name]['Name'],
'Customer Address': Customers[customer_name]['Address'],
'Customer ID': Customers[customer_name]['ID'],
'Total Orders': Customers[customer_name]['Orders'],
'Total Amount': Customers[customer_name]['TotalAmount']}])
openFile()
file.close()
file1.close()
file2.close()
I have tried adding a Customers[Customer_Name]['Order_Price'] but it did not work
Your issue is with the Total_Amount variable. Its value is kept from the last iteration and assigned to the next customer. You need to retrieve it from your Customers dictionary and then update the value in the dictionary after.
if Customer_Name in Customers:
Customers[Customer_Name]['Orders'] += 1
# Customers[Customer_Name]['TotalAmount'] = Total_Amount # This is where the error was
else:
Customers[Customer_Name] = {}
Customers[Customer_Name]['Name'] = Customer_Name
Customers[Customer_Name]['Address'] = Customer_Address
Customers[Customer_Name]['ID'] = uuid.uuid1()
Customers[Customer_Name]['Orders'] = 1
Customers[Customer_Name]['TotalAmount'] = 0
Total_Amount = Customers[Customer_Name]['TotalAmount'] # retrieve value here
Order_Price = float(input("Total amount of order:"))
ORDERS_FROM_EMPLOYEE += 1
print(Customer_Name, "has ordered {} time(s)".format(Customers[Customer_Name]['Orders']))
Total_Amount = Order_Price + Total_Amount
Customers[Customer_Name]['TotalAmount'] = Total_Amount # update value here
I am programming an experiment on Otree in which players type in their names and participate in a competition on who donate the most threes. The trees are entered via a form field. Round number is a predefined variable. And every player gets an id when he enters the experiment by default (starting from 1)
I already programmed the whole code and it works with up to 5 participants, but now I should program it for up to 8 participants. When I try to enter the number of participants on Otree, I receive the error message "index error: list index out of range".
Error occurs in the line matrix[p.id_in_group - 1][0] = p.name
matrix[p.id_in_group - 1][self.round_number] = p.cumulative_donated_trees
so I guess the initialization of the matrix is wrong?
I just want to have a Matrix with 2 columns: names and trees (and index column of course) and n rows (n = number of players)```
models.py:
class Donation(Page):
try:
form_model = 'player'
form_fields = ['donation']
def vars_for_template(self):
names = []
trees = []
sortedtrees = []
anzahlspalten = 0
for p in self.subsession.get_players():
if self.round_number == 1:
matrix[p.id_in_group - 1][0] = p.name
matrix[p.id_in_group - 1][self.round_number] = p.cumulative_donated_trees
for i in range(0, Constants.number_of_players):
names.append(matrix[i][0])
trees.append(matrix[i][self.round_number])
sortedtrees = sorted(trees, reverse=True)
anzahlspalten = len(sortedtrees)
for l in range(0, anzahlspalten):
if self.player.cumulative_donated_trees == sortedtrees[l]:
self.player.current_position = str(l + 1)
models.py:
name = models.StringField(label="Your first name:")
transcribed_text = models.LongStringField()
levenshtein_distance = models.IntegerField()
guthaben = models.CurrencyField(initial=c(0))
cumulative_guthaben = models.CurrencyField()
cumulative_donation = models.FloatField(null=True)
right_answer = models.BooleanField()
right_answer_text = models.StringField()
treatmentgroup = models.StringField()
donation = models.FloatField(min=c(0))
no_trees = models.FloatField(initial=0.0)
cumulative_donated_trees = models.FloatField()
current_position = models.StringField()
spielstand = models.StringField()
Treceback:
File "c:\users\wiwi-admin\appdata\local\programs\python\python37\lib\site-packages\otree\views\abstract.py" in get_context_data
338. user_vars = self.vars_for_template()
File "C:\Users\Wiwi-Admin\Desktop\Backup Version 2 - Competition WITHIN Treatmentgroups\Master thesis code\__pycache__\oTree\my_environmental_surveyTG4\pages.py" in vars_for_template
252. matrix[p.id_in_group - 1][0] = p.name
Exception Type: IndexError at /p/tgv0j88z/my_environmental_surveyTG4/Donation/7/
Exception Value: list index out of range
I am trying to get data from a txt file and put it into a dataframe. Text file looks something like this:
******************************************************************************************************************************
DATE BUY:2018/05/26
****************************************************************************************************************************
STORE: DUBIDUBI SAILOR: 123456
***********************************************************************************************************************
< CLIENT >
NAME CLIENT MEMBER TYPE MEMBER NUMBER: 89101112
ANTONY STARK 1
<PRODUCTS>
NUM-PRODUCTS
6
< ADDRESS TO SEND>
186 FLEET STREET
-----------------------------------------------------------------------------------------------------------------------
< CLIENT >
NAME CLIENT MEMBER TYPE MEMBER NUMBER: 13141516
THOR 2
<PRODUCTS>
NUM-PRODUCTS
2
< ADDRESS TO SEND>
1800 PENNSYLVANIA STREET
<SERVICES>
NUM-SERVICE TYPE OF SERVICE
64 DEVOLUTION
*****************************************************************************************************************************
I want to get a dataframe containing a list of all the clients information that were assisted by same sailor in same store.
What does works: below code reads the text line by line and extract the information of each line.
data []
global STORE, DATE_BUY, SAILOR, CLIENT, MEMBER_NUM, NUM_PRODUCTS, ADDRESS, NUM_SERVICE, TYPE_MEMB, TYPE_SERV
STORE = ""
DATE_BUY = ""
SAILOR = ""
CLIENT = ""
MEMBER_NUM = ""
NUM_PRODUCTS = ""
ADDRESS = ""
NUM_SERVICE = ""
TYPE_MEMB = ""
TYPE_SERV = ""
with open ('myfile', 'r') as txt_file:
read_file = txt_file.readlines()
for i in range(0, len(read_file)):
line = read_file[i]
z = line[0:50]
a = line[0:9]
b = line[0:42]
c = line[112:132]
d = line[0:14]
e = line[0:14]
dif_client = line[0:58]
if a == " STORE":
STORE = line[10:28]
SAILOR = line[30:45]
elif c == " DATE BUY":
DATE_BUY = line[133:145]
elif b == " NAME CLIENT"
nextline = read_file[i + 1]
CLIENT = nextline[0:57]
MEMBER_NUM = nextline[96:126]
TYPE_MEMB = nextline[79:86]
elif d == " < ADDRESS":
nextline = read_file[i + 1]
ADDRESS = nextline[0:63]
elif e == " < PRODUCTS":
nextline = read_file[i + 1]
NUM_PRODUCTS = nextline[0:24]
elif f == " <SERVICES":
nextline = read_file[i + 1]
NUM_SERVICE = nextline[]
TYPE_SERV = nextline[]
data.append({'Store':STORE, 'Sailor':SAILOR, 'Date_Buy':DATE_BUY, 'Client':CLIENT, 'Member_Num':MEMBER_NUM,
'Type_Memb':TYPE_MEMB, 'Address':ADDRESS, 'Products':NUM_PRODUCTS,'Num_Serv':NUM_SERVICE, 'Type_Serv':TYPE_SERV})
df = pd.DataFrame(data)
What does NOT works: when using a nested while loop to extract information of each client assisted by a sailor my code simply does not end running. The code that does not work is:
data []
global STORE, DATE_BUY, SAILOR, CLIENT, MEMBER_NUM, NUM_PRODUCTS, ADDRESS, NUM_SERVICE, TYPE_MEMB, TYPE_SERV
STORE = ""
DATE_BUY = ""
SAILOR = ""
CLIENT = ""
MEMBER_NUM = ""
NUM_PRODUCTS = ""
ADDRESS = ""
NUM_SERVICE = ""
TYPE_MEMB = ""
TYPE_SERV = ""
with open ('myfile', 'r') as txt_file:
read_file = txt_file.readlines()
for i in range(0, len(read_file)):
line = read_file[i]
z = line[0:50]
a = line[0:9]
b = line[0:42]
c = line[112:132]
d = line[0:14]
e = line[0:14]
dif_client = line[0:58]
while dif_client != " < CLIENT >":
if a == " STORE":
STORE = line[10:28]
SAILOR = line[30:45]
elif c == " DATE BUY":
DATE_BUY = line[133:145]
elif b == " NAME CLIENT"
nextline = read_file[i + 1]
CLIENT = nextline[0:57]
MEMBER_NUM = nextline[96:126]
TYPE_MEMB = nextline[79:86]
elif d == " < ADDRESS":
nextline = read_file[i + 1]
ADDRESS = nextline[0:63]
elif e == " < PRODUCTS":
nextline = read_file[i + 1]
NUM_PRODUCTS = nextline[0:24]
elif f == " <SERVICES":
nextline = read_file[i + 1]
NUM_SERVICE = nextline[]
TYPE_SERV = nextline[]
data.append({'Store':STORE, 'Sailor':SAILOR, 'Date_Buy':DATE_BUY, 'Client':CLIENT, 'Member_Num':MEMBER_NUM,
'Type_Memb':TYPE_MEMB, 'Address':ADDRESS, 'Products':NUM_PRODUCTS,'Num_Serv':NUM_SERVICE, 'Type_Serv':TYPE_SERV})
df = pd.DataFrame(data)
The desired output should look something like this. I know that each client information comes when the word < CLIENT > appears in text.
Date_buy Store Sailor Client Member_Number Num_Products Address_to_send num_Service type_serv
2018/05/26 dubidubi 123456 ANTONY STARK 89101112 6 186 FLEET STREET
2018/05/26 dubidubi 123456 THOR 13141516 2 1800 PENNSYLVANIA STREET 64 DEVOLUTION
Thanks for the description. The problem is in the infinite loop you built:
dif_client = line[0:58]
while dif_client != " < CLIENT >":
if a == " STORE":
...
dif_client doesn't change within the loop. There is no break or other exit, only the while condition (which is good design). Therefore, once you get into the loop, you have no way to leave: dif_client is constant.
Your logic is incorrect: you have two loops that are trying to walk through the lines of the file:
for i in range(0, len(read_file)):
...
while dif_client != " < CLIENT >":
# Process one line
The body of the while is designed to process one line. When you're done with that, you need to go to the next iteration of the for to get the next line. Finding a CLIENT line is a if decision, not a loop.