I'm currently working on a project, which inputs from a file, the following information:
10015, John, Smith, 2, 3.01
10208, Patrick, Green, 1, 3.95
10334, Jane, Roberts, 4, 3.81
What I need to do is split this information, store each value separately, then print it out to the screen or file based on what the user needs.
The function which should split and then assign information is this:
def fetchRecord( self ):
#Read the first line of the record.
line = self._inputFile.readline()
line = input.split( ', ' )
if line == "":
return None
#If there is another record, create a storage object and fill it
student = StudentRecord()
student.idNum = int( line[0] )
student.firstName = line[1]
student.lastName = line[2]
student.classCode = int( line[3] )
student.gpa = float( line[4] )
return student
The error I'm currently getting is the following:
builtins.ValueError: invalid literal for int() with base 10: '10015, John, Smith, 2, 3.01\n'
The entire code I'm calling is:
class StudentFileReader:
#Create new student reader instance.
def __init__( self, inputSrc ):
self._inputSrc = inputSrc
self._inputFile = None
#Open a connection to the input file.
def open( self ):
self._inputFile = open( self._inputSrc, "r" )
#Close the connection to the input file.
def close( self ):
self._inputFile.close()
self._inputFile = None
#Extract all student records and store them in a list.
def fetchAll( self ):
theRecords = list()
student = self.fetchRecord()
while student != None:
theRecords.append( student )
student = self.fetchRecord()
return theRecords
#Extract the next stuent record from the file.
def fetchRecord( self ):
#Read the first line of the record.
line = self._inputFile.readline()
print ( line )
line = line.split( ',' )
print ( line )
if line == "":
return None
#If there is another record, create a storage object and fill it
student = StudentRecord()
student.idNum = int( line[0] )
student.firstName = line[1]
student.lastName = line[2]
student.classCode = int( line[3] )
student.gpa = float( line[4] )
return student
class StudentScreenWriter:
#Prints the student report to screen.
def printReport( theList ):
#The class names associated with the class codes.
classNames = ( None, "Freshman", "Sophomore", "Junior", "Senior" )
#Print the header.
print( "LIST OF STUDNETS".center(50) )
print( "" )
print( "%-5s %-25s %-10s %-4s" % ('ID', 'NAME', 'CLASS', 'GPA' ) )
print( "%5s %25s %10s %4s" % ('-' * 5, '-' * 25, '-' * 10, '-' * 4) )
#Print the body.
for record in theList:
print( "%5d %-25s %-10s %4.2f" % (record.idNum, record.lastName + ", " + record.firstName, classNames[record.classCode], record.gpa) )
#Add a footer.
print( "-" * 50 )
print( "Number of students:", len(theList) )
class StudentFileWriter:
#Prints the student report to file.
def printReport( theList, out ):
for record in theList
record.idNum = str(record.idNum)
record.lastName = str(record.lastName)
record.firstName = str(record.firstName)
record.classCode = str(record.classCode)
record.gpa = str(record.gpa)
out.write( record.idNum + ", " + record.lastName + ", " + record.firstName + ", " + record.classCode + ", " + record.gpa )
out.write( "\n" )
class StudentRecord:
def __init__( self ):
self.idNum = None
self.firstName = None
self.lastName = None
self.classCode = None
self.gpa = None
not the answer you are looking for but you should consider
class StudentRecord:
def __init__(self,idNum=-1,firstName="unknown",lastName="Unknown",classCode=-1,gpa=-1):
self.idNum = idNum
self.firstName = firstName
self.lastName = lastName
self.classCode = classCode
self.gpa = gpa
#... The rest of your class
with csv module
import csv
with open("some.txt") as f:
reader = csv.reader(f)
for student_details in reader:
student = StudentRecord(*student_details)
without csv module
with open("some.txt") as f:
for line in f:
student_details = line.split(",")
student = StudentRecord(*student_details)
testing with your data
class StudentRecord:
def __init__(self,idNum=-1,firstName="unknown",lastName="Unknown",classCode=-1,gpa=-1):
self.idNum = idNum
self.firstName = firstName
self.lastName = lastName
self.classCode = classCode
self.gpa = gpa
def __str__(self):
return "#%s:%s, %s | %s = %s"%(
self.idNum,self.lastName,self.firstName,
self.classCode,self.gpa
)
def __repr__(self):
return "<Student Record (%s %s)>"%(
self.firstName,self.lastName
)
with open("txt_data.txt") as f:
for line in f:
student_data = line.strip().split(", ")
student = StudentRecord(*student_data)
print "Student:",student
outputs:
Student: #10015:Smith, John | 2 = 3.01
Student: #10208:Green, Patrick | 1 = 3.95
Student: #10334:Roberts, Jane | 4 = 3.81
You need to change the line
line = input.split( ', ' )
to
line = line.split( ',' )
and move it after
if line == "":
return None
input is undefined in the current context.
you may consider this for spliting the data (used your data)
>>> for line in f:
li1 = []
for part in line.split(','):
part = part.strip()
li1.append(part)
li2.append(li1)
>>> for i in li2:
print i
['10015', 'John', 'Smith', '2', '3.01']
['10208', 'Patrick', 'Green', '1', '3.95']
['10334', 'Jane', 'Roberts', '4', '3.81']
li1andli2are lists. And f is the input file in which each line has a record/data.
You will now have the list. You can use the same method(s) to get and process the name,class code,gpa etc.
Related
class StockPicking(models.Model): _inherit = ['stock. Picking'] _description = 'test.test' _order = 'id'
def _default_group_id(self): if self.env.context.get('default_picking_id'): return self.env['stock. Picking'].browse(self.env.context['default_picking_id']).group_id.id return False
1.Inventory--->tranfers--->create---->
quantity_done(Done) value fetch
employee_id = fields.Many2one('hr.employee', 'Employee')
product_id = fields.Many2one('product. Product', string='Product', check_company=True)
department_id = fields.Many2one('hr. Department', string='Department')
product_id = fields.Many2one('product.product', string='Product', check_company=True)
employee = fields. Char('hr.employee', related='employee_id.name')
department = fields. Char('hr. Department', related='department_id.name')
products = fields.Char('product.product', related='product_id.name')
product_uom = fields.Many2one('uom.uom', "UoM", required=True,
domain="[('category_id', '=', product_uom_category_id)]")
quantity_done = fields. Float('Quantity Done', compute='_quantity_done_compute', digits='Product Unit of Measure',
inverse='_quantity_done_set')
def change_release_date(self):
# stock_move = self.env['stock. Move'].search([('product_id', '=', self._ids)])
new = 'Employee Name:-' + str(self. Employee)
new1 = 'Department:-' + str(self. Department)
new2 = ' Date:-' + self.scheduled_date.strftime(
'%Y-%m-%d,%H:%M:%S %p')
new3 = 'Asset Name:-' + str(self. Products)
new4 = 'Reference No:-' + self.name
new5 = 'Quantity:-' + str(self.quantity_done)
new_data = " " + new + "\n " + new1 + "\n" + new2 + "\n " + new3 + "\n " + new4 + "\n" + " " + new5
img = qrcode.make(new_data)
print(new_data)
img.save('C:/odoo/custom_addons/qr/qr1.png')
def _quantity_done_compute(self):
if not any(self._ids):
# onchange
for move in self:
quantity_done = 0
for move_line in move._get_move_lines():
quantity_done += move_line.product_uom_id._compute_quantity(
move_line.qty_done, move.product_uom, round=False)
move.quantity_done = quantity_done
else:
# compute
move_lines_ids = set()
for move in self:
move_lines_ids |= set(move._get_move_lines().ids)
data = self.env['stock.move.line'].read_group(
[('id', 'in', list(move_lines_ids))],
['move_id', 'product_uom_id', 'qty_done'], ['move_id', 'product_uom_id'],
lazy=False
)
rec = defaultdict(list)
for d in data:
rec[d['move_id'][0]] += [(d['product_uom_id'][0], d['qty_done'])]
for move in self:
uom = move.product_uom
move.quantity_done = sum(
self.env['uom.uom'].browse(line_uom_id)._compute_quantity(qty, uom, round=False)
for line_uom_id, qty in rec.get(move.ids[0] if move.ids else move.id, [])
)
def _get_move_lines(self):
self.ensure_one()
if self.picking_type_id.show_reserved is False:
return self.move_line_nosuggest_ids
return self.move_line_ids
I have solve this Question Ans and generate QRCode
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
I am trying to automate a functions based on what input is received but I'm getting an error when I try to pass the input as and arg for a function. Heres an example of what Im trying to do
var ='hello world'
def example(data):
#function code
example(var)
thats a basic usage of what Im doing and its returning an error like
var is not defined
here is my actual code
import AriaAudioConfig as Ariaconfig
import AriaMathModule as AriaMath
import AriaLocationModule as AriaLocation
import AriaNLPModule as AriaNLP
from inspect import getmembers, isfunction
import re
import pandas as pd
import csv
from typing import Awaitable, Callable, TypeVar
location = ['geolocatecity','citydiff','locate', 'location', 'where is', 'far', 'distance']
math = ['calculate', 'add', 'subtract', 'multiply', 'divide', 'addition', 'subtraction', 'multiplication', 'division', 'square-root', 'power', 'squared', 'minus']
audio = ['volume','speak', 'sound']
nlp = ['translate', 'translation', 'language', 'english', 'spanish', 'french']
locdict = {'geolocatecity':'blabla','citydiff':'blabla'}
state = 0
city2 = 0
file = pd.read_csv('geolocations.csv')
def dataProcess(data):
global state
global city2
datasearch = data.split()
argsearch = datasearch
datalength = len(datasearch)
for i in range(datalength):
if datasearch[i] in location:
data = datasearch[i]
datacom = typeremoval(functiongrep(AriaLocation))
datacom = str(datacom).split()
datalen = len(datacom)
with open('geolocations.csv', 'rt') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
for field in row[0]:
for i in range(datalength):
if argsearch[i] == row[0]:
try:
if city in locals():
city2 = argsearch[i]
except:
city = argsearch[i]
if argsearch[i] == row[1]:
state = argsearch[i]
if argsearch[i] == row[2]:
country = argsearch[i]
f.close()
for i in range(datalen):
if str(data) in str(datacom[i]):
activefunction = datacom[i]
if state != 0:
eval('AriaLocation.' + activefunction +'(' + city + ',' + state + ',' + country + ')')
elif city2 != 0:
eval('AriaLocation.' + activefunction + '(' + city + ',' + city2 + ')')
else:
print('uh-oh something went wrong')
elif datasearch[i] in math:
data = datasearch[i]
datacom = typeremoval(functiongrep(AriaMath))
print(data)
if data in datacom:
print('found')
elif datasearch[i] in audio:
data = datasearch[i]
datacom = typeremoval(functiongrep(Ariaconfig))
elif datasearch[i] in nlp:
data = datasearch[i]
datacom = typeremoval(functiongrep(AriaNLP))
#dataProcess('Aria how far am I from Arizona')
def functiongrep(function):
string = ''
functions_list = [o for o in getmembers(function) if isfunction(o[1])]
flen = len(functions_list)
for i in range(flen):
head, sep, tail = str(functions_list[i]).partition('<')
string = string + head
return string
def typeremoval(function):
func = str(function)
func = str(''.join(func))
func = re.sub("[',()]", '', func)
return func
dataProcess('locate Scottsdale Arizona USA')
I want dataProcess() to activate different commands based on what is given as the input.
Exception has occurred: NameError
name 'Scottsdale' is not defined
File "/Users/timyc1/Desktop/DeadIdeas/smartroom/Seavernet/Aria/AriaProcessingModule.py", line 58, in dataProcess
eval('AriaLocation.' + activefunction +'(' + city + ',' + state + ',' + country + ')')
File "/Users/timyc1/Desktop/DeadIdeas/smartroom/Seavernet/Aria/AriaProcessingModule.py", line 95, in <module>
dataProcess('locate Scottsdale Arizona USA')
Don't use eval for this. eval is almost never the solution.
if state != 0:
getattr(AriaLocation, activefunction)(city, state, country)
elif city2 != 0:
getattr(AriaLocation, activefunction)(city, cit2)
else:
print('uh-oh something went wrong')
error section--> student_grade_system = StudentGradeSystem(sys.argv1)
errored place-->
Traceback (most recent call last):
File "C:\Users\Daphnie\Desktop\Python_code\12\student_grade\grade_system.py", line 111, in
main()
File "C:\Users\Daphnie\Desktop\Python_code\12\student_grade\grade_system.py", line 105, in main
student_grade_system = StudentGradeSystem(sys.argv1)
IndexError: list index out of range
Code:
import sys
from student import Student
class StudentGradeSystem(object):
def __init__(self, score_file):
self._score_file = score_file
self._students = []
self._class_avg = 0.0
self._kor_avg = 0.0
self._eng_avg = 0.0
self._math_avg = 0.0
self._register_students()
def _register_students(self):
with open(self._score_file, "rt") as fp:
lines = fp.readlines()
for line in lines:
items = (line.strip()).split(",")
num = items[0]
name = items[1]
kor = int(items[2])
eng = int(items[3])
math = int(items[4])
student = Student(num, name, kor, eng, math)
self._students.append(student)
def _calculate_student_order(self):
temp_students = sorted(self._students, key = lambda x: x.total, reverse = True)
order = 1
for student in temp_students:
student.order = order
order = order + 1
self._students = temp_students
def _calculate_class_avg(self):
total = 0
for student in self._students:
total = total + student.total
self._class_avg = total / len(self._students)
def _calculate_kor_avg(self):
total = 0
for student in self._students:
total = total + student.kor
self._kor_avg = total / len(self._students)
def _calculate_eng_avg(self):
total = 0
for student in self._students:
total = total + student.eng
self._eng_avg = total / len(self._students)
def _calculate_math_avg(self):
total = 0
for student in self._students:
total = total + student.math
self._math_avg = total / len(self._students)
def _calculate_class_information(self):
self._calculate_class_avg()
self._calculate_kor_avg()
self._calculate_eng_avg()
self._calculate_math_avg()
def process(self):
self._calculate_student_order()
self._calculate_class_information()
def output_result(self, output_file):
student_output_format = "번호: {:2}, 이름: {}, 국어: {}, 영어: {}, 수학: {}, 총점: {}, 평균: {:.2f}, 등수: {}\n"
with open(output_file, "wt") as fp:
for student in self._students:
student_output = student_output_format.format(student.num, student.name, student.kor, student.eng,
student.math, student.total, student.avg, student.order)
fp.write(student_output)
fp.write("\n")
fp.write("반 평균: %.2f\n" % self._class_avg)
fp.write("국어 평균: %.2f\n" % self._kor_avg)
fp.write("영어 평균: %.2f\n" % self._eng_avg)
fp.write("수학 평균: %.2f\n" % self._math_avg)
print("성적 처리가 끝났습니다.")
def main():
student_grade_system = StudentGradeSystem(sys.argv[1])
student_grade_system.process()
student_grade_system.output_result(sys.argv[2])
if __name__ == "__main__":
main()
input("end")
What don't you understand exactly ? The error message is quite clear: you have an IndexError (you're trying to access a non-existant item in a list, tuple or other similar indexed sequence) at line 105, which is
student_grade_system = StudentGradeSystem(sys.argv[1])
In this line there's only one indexed access - sys.argv[1] - so it's obviously the culprit. Since your program obviously expects some arguments to be passed, it's your responsability to make sure 1. they are documented and 2. there are effectively passed to the program (which is obviously not the case here).
The Code Below I wrote takes input from a sample file which contains First and Last names. Then it converts those names to sample emails. For some reason the Script keeps printing the same Last name over and over.
namess.txt looks like this:
firstname,lastname
CODE:
import os, re, time, getpass, linecache
Original = os.path.join(os.path.expanduser('~'), 'Desktop','namess.txt')
File = os.path.join(os.path.expanduser('~'), 'Desktop','output.txt')
badNames = []
Names = []
def RemCommas():
outfile = open(os.path.join('C:\\', 'Users', getpass.getuser(), 'Desktop','output.txt'),'w')
Filedata = open(Original).read()
outfile.write(re.sub(',', ' ', Filedata))
outfile.close()
def ClassNum():
count = 6
Year = int(time.strftime('%Y'))
Class = str((Year - 2013) + 6)
return Class
def ReadStoreFile():
i = 0
OpenFile = open(File)
LenFile = len(OpenFile.readlines())
while i < LenFile:
i += 1
badNames.append(linecache.getline(File, i))
def CleanNames():
i = 0
while i < len(badNames):
cleaned = badNames[i].rstrip()
Names.append(cleaned)
i += 1
def NamePrint():
Interns = 'makchessclub.org'
arrayname = []
i = 0
j = 0
m = 0
while m < len(Names):
Name = Names[m]
Name = Name.lower()
InternName = Name[0] + Name[1]
#------------Checking for space and first name--
while i < len(Name):
if Name[i] == ' ':
i = Name.index(' ')
break;
i += 1
#---------------adding last name in an array----
Namelen = len(Name) - (i+1)
while j < Namelen:
arrayname.append(Name[i+1])
j += 1
i += 1
#---------------Final Name Print----------------
Lastname = ''.join(arrayname)
#print arrayname
#Lastname = Lastname.strip(' ')
#print InternName + Lastname + ClassNum() + Interns
file = open('C:\\Users\\username\\Desktop\\emails.txt', 'a')
file.write(InternName + Lastname + ClassNum() + Interns + '\n')
file.close()
m += 1
RemCommas()
ReadStoreFile()
CleanNames()
NamePrint()
print ''
os.system('pause')
The reason the last name doesn't change is because you are not resetting arrayname in your loop. You keep appending names to it, and the program picks the first one. So you should put your arrayname = [] after the while m < len(Names):
I guess this what you are trying to do:
import os
import re
import time
def create_mails(input_path, output_path, year, addr):
with open(input_path, 'r') as data:
mail = re.sub(r'(\w+)\s*,\s*(\w+)\n?', r'\1\g<2>%s%s\n' % (year, addr), data.read())
with open(output_path, 'w') as output:
output.write(mail.lower())
print 'Mail addresses generated and saved to', output_path
Demo:
create_mails(
os.path.join(os.path.expanduser('~'), 'Desktop', 'namess.txt'),
os.path.join(os.path.expanduser('~'), 'Desktop', 'output.txt'),
str(int(time.strftime('%Y')) - 2013 + 6),
'#makchessclub.org'
)
If namess.txt is something like this:
First, Last
John,Doe
Spam, Ham
Cabbage, egg
Then output.txt is going to be like this:
firstlast6#makchessclub.org
johndoe6#makchessclub.org
spamham6#makchessclub.org
cabbageegg6#makchessclub.org