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
Related
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 doing a POS machine which save the data in a text file. After customer buy item, the total quantity of the item in the text file will minus the quantity of the customer brought, but after I trying the code can works but the stock quantity in the text file remain unchanged. So, I found some answer from this SO question Reducing quantity in text file
, it works for them but mine can't. What gone I to do for my code work.
This is the contein of my text file named razershop.txt(id, name, price, quantity):
1 , Razer Deathadder V2, 349.00 , 100
2 , Razer Viper Ultimate, 419.00 , 105
3 , Razer Basilink Ulti, 599.00 , 35
4 , Razer Viper Mini, 139.00 , 295
5 , Raazer Deathadder X, 76.90 , 592
I used all_products to open my file:
all_products = [line.strip().split(',') for line in open('razershop.txt','r').readlines()]
This is the decrement item function code:
def decrement_item(item_id, quantity):
with open('razershop.txt', 'r') as fin:
# indexes for id and quantity
index_id = 0
index_quantity = 3
# output buffer
output = []
# Add headaer to output buffer
header = fin.readline().rstrip()
output.append(header) # header without '\n' at end of line
bfound_item = False
for line in fin:
# Check each line for item_id then upadte quantity
line = line.rstrip()
if not bfound_item:
# Only process if item_id has not been found yet
# Break line into separate fields
row = line.split()
current_id = row[index_id]
if current_id == item_id:
# Found item
# Check if sufficiente quantity
current_quantity = int(row[index_quantity])
if current_quantity >= quantity:
# Decrement quantity
current_quantity -= quantity
row[index_quantity] = str(current_quantity)
line = ' '.join(row)
bfound_item = True
else:
# Insufficient quantity for update
s = f"Sorry, available quantity is only {int(row[index_quantity])}"
raise Exception(s)
# Add line to output
output.append(line) # add copy since row changes with loop
# Update inventory file
with open('razershop.txt', 'w') as fout:
for line in output:
fout.write(line + '\n')
This is my Pos machine code which generate bill and will decrease the stock after customer buy it:
while(True):
banner()
choice = int(input("Please enter your option: "))
if choice == 1:
display_all()
elif choice == 2:
display_all()
print("Press 0 for payment")
item_lst = []
price_lst = []
quantity_lst = []
total_price = 0
prod_id = 999
while prod_id != 0:
prod_id = int(input("Enter the Product ID: "))
for item in all_products:
if int(item[0]) == prod_id:
quantity = int(input("Please enter the quantity: "))
item_lst.append(item[1])
quantity_lst.append(quantity)
price_q = float(item[2]) * quantity
price_lst.append(price_q)
total_price = total_price + price_q
decrement_item(prod_id , quantity)
order_summary(item_lst , price_lst , total_price , quantity_lst)
print(" ")
conf = input("Please confirm your order(Y/N): ")
if conf == "Y":
member = input("Do you have membership(Y/N): ")
if member == "Y":
total_price = total_price * 0.9
payment = float(input("Amount received: "))
change = payment - total_price
generate_bill(item, total_price, item_lst , price_lst , quantity_lst ,change , payment)
print(" ")
print("Thanks For shopping with Us :)")
sys.exit(0)
else:
payment = float(input("Amount received: "))
change = payment - total_price
generate_bill(item, total_price, item_lst , price_lst , quantity_lst ,change , payment)
print(" ")
print("Thanks For shopping with Us :)")
sys.exit(0)
else:
print("Continue Exploring the shop")
Output:
Upper output for customer to enter the item they want
Below part of the output which generate bill
(Sorry guys the output I can't put it in image form becuase SO not allow me so they changed my image to a link)
I had tried delete the with open('razershop.txt', 'r') as fin: and header = fin.readline().rstrip() and ( row = line.split() and change all the row variable to line fromfor line in fin: # Check each line for item_id then upadte quantity line = line.rstrip()from the decrement_item function. It end up with a infinity loop and last time I forgot what I had done with the code from the decrement_ item function the whole text in the txt file gone. I just want to know what should I do to make this work?
This question already has answers here:
Replacing instances of a character in a string
(17 answers)
Closed 2 years ago.
I am working with streamlit and python to create webpage of our code but it is showing me some error to fix this error I give different keys to every input arguments but still it showing me the error.
I have given the different keys to every input but it showing in error as below:
DuplicateWidgetID: There are multiple identical st.selectbox widgets with key='155'.
To fix this, please make sure that the key argument is unique for each st.selectbox you create.
Traceback:
File "C:\Users\jaiklen\Desktop\IP_Assignment_2\web.py", line 29, in <module>
query = st.selectbox("Please Enter Your Query Number or enter -1 to exit: ",[-1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],key = "155")
Below is my python code with streamlit:
import json
import streamlit as st
import a2 as a
st.title("Welcom to our database")
st.write("There are some queries below :")
st.write("1. read_data_from_file")
st.write("2. filter_by_first_name")
st.write("3. filter_by_last_name")
st.write("4. filter_by_full_name")
st.write("5. filter_by_age_range")
st.write("6. count_by_gender")
st.write("7. filter_by_address")
st.write("8. find_alumni")
st.write("9. find_topper_of_each_institute")
st.write("10. find_blood_donors")
st.write("11. get_common_friends")
st.write("12. is_related")
st.write("13. delete_by_id")
st.write("14. add_friend")
st.write("15. remove_friend")
st.write("16. add_education")
query = 0
while(query != -1):
query = st.selectbox("Please Enter Your Query Number or enter -1 to exit: ",[-1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],key = "155")
records = a.read_data_from_file()
if(query == 2):
first_name = st.text_input("Enter the first name",key = "2")
st.write(a.filter_by_first_name(records, first_name))
elif(query == 3):
last_name = st.text_input("Enter the last name",key = "3")
st.write(a.filter_by_last_name(records, last_name))
elif(query == 4):
full_name = st.text_input("Enter the full name",key = "4")
st.write(a.filter_by_full_name(records, full_name))
elif(query == 5):
min_age = int(st.text_input("Enter the minimum age",key = "5"))
max_age = int(st.text_input("Enter the maximum age",key = "6"))
st.write(a.filter_by_age_range(records, min_age, max_age))
elif(query == 6):
#full_name = st.text_input("Enter the full name")
st.write(a.count_by_gender(records))
elif(query == 7):
address = {}
house_no = st.text_input("Enter house number or leave empty: ",key = "7")
block = st.text_input("Enter block or leave empty: ",key = "8")
town = st.text_input("Enter town or leave empty: ",key = "9")
city = st.text_input("Enter city or leave empty: ",key = "10")
state = st.text_input("Enter state or leave empty: ",key = "11")
pin_code = st.text_input("Enter pin code or leave empty: ",key = "12")
if(len(house_no) != 0):
address["house_no"] = int(house_no)
if(len(block) != 0):
address["block"] = block
if(len(town) != 0):
address["town"] = town
if(len(city) != 0):
address["city"] = city
if(len(state) != 0):
address["state"] = state
if(len(pin_code) != 0):
address["pin_code"] = int(pin_code)
st.write(len(a.filter_by_address(records, address)))
elif(query == 8):
institute_name = st.text_input("Enter the institute name",key = "13")
st.write(a.find_alumni(records, institute_name))
elif(query == 9):
#full_name = st.text_input("Enter the full name")
st.write(a.find_topper_of_each_institute(records))
elif(query == 10):
receiver_person_id = int(st.text_input("Enter the full name",key = "14"))
st.write(a.find_blood_donors(records, receiver_person_id))
elif(query == 11):
list_of_ids = list(map(int,st.text_input("Enter the full name",key = "15").split()))
st.write(a.get_common_friends(records, list_of_ids))
elif(query == 12):
person_id_1 = int(st.text_input("Enter the person id 1",key = "16"))
person_id_2 = int(st.text_input("Enter the person id 2",key = "17"))
st.write(a.is_related(records, person_id_1, person_id_2))
elif(query == 13):
person_id = int(st.text_input("Enter the person id",key = "18"))
records = a.delete_by_id(records, person_id)
elif(query == 14):
person_id = int(st.text_input("Enter the person id",key = "19"))
friend_id = int(st.text_input("Enter the friend id",key = "20"))
records = a.add_friend(records, person_id, friend_id)
elif(query == 15):
person_id = int(st.text_input("Enter the person id",key = "21"))
friend_id = int(st.text_input("Enter the friend id",key = "22"))
records = a.remove_friend(records, person_id, friend_id)
elif(query == 16):
person_id = int(st.text_input("Enter the person id",key = "23"))
institute_name = st.text_input("Enter the institute name",key = "24")
ongoing = bool(st.text_input("If ongoing enter True else entre False",key = "25"))
percentage = float(st.text_input("Enter percentage if ongoing False, else enter 0",key = "26"))
records = a.add_education(records, person_id, institute_name, ongoing, percentage)
I anyone knows where is the error please let me know.
and thank you to at least read my problem.
Just replace every . with [.]:
ip=ip.replace(".","[.]")
Below is the code I am working with and although there are no errors in the console output it still doesn't return anything there. Why is there no output with the code? Is there anything I need to change or fix. I think I imported the scanner correctly but there may be an issue with that. Thank you!
import sys
from scanner import Scanner
from functools import cmp_to_key
class Tweet:
def __init__(self, tweeter, tweet, time):
self.tweeter = tweeter[1:]
self.tweet = tweet
self.time = time
def __str__(self):
return self.tweeter+" "+self.time
def display(self):
return self.tweeter+" " +self.tweet
def create_record(s):
tweets = []
tweeter = s.readtoken()
tweet1count = 0
while tweeter != "":
tweet = s.readstring()
t1 = Tweet(tweeter, tweet, s.readline())
tweet1count += 1
tweeter = s.readtoken()
tweets.append(t1)
return tweets
def read_records(file):
s = Scanner(file)
return create_record(s)
def is_more_recent(t1, t2):
year, month, day, time = t1.time.split()
month = ("0" + month)[-2:]
day = ("0" + day)[-2:]
timestamp1 = year + month + day + time
year, month, day, time = t2.time.split()
month = ("0" + day)[-2:]
day = ("0" + day)[-2:]
timestamp2 = year + month + day + time
return timestamp1 > timestamp2
def merge_and_sort_tweets(tweets1, tweets2):
tweets = tweets1 + tweets2
cmp_items_py3 = cmp_to_key(is_more_recent)
tweets.sort(key = cmp_items_py3)
return tweets
def write_records(file, tweets):
file = open(file, "w+")
for t in tweets:
file.write(str(t))
def main():
print("Reading Files")
tweets1 = read_records(sys.argv[1])
tweets2 = read_records(sys.argv[2])
tweet1count = len(tweets1)
tweet2count = len(tweets2)
if tweet1count > tweet2count:
print("tweet1.txt contained the most tweets with" , tweet1count)
elif tweet1count < tweet2count:
print("tweet2.txt contained the most tweets with" , tweet2count)
else:
print("tweet1.txt contains ", tweet1count, "tweets. ")
print("tweet2.txt contains ", tweet2count, "tweets. ")
print("Merging files...")
tweets = merge_and_sort_tweets(tweets1, tweets2)
print("Writing file...")
write_records(sys.argv[3], tweets)
print("File writtem. Displying", min(5, len(tweets)),"earliest tweeters and tweets.")
for i in range(min(5, len(tweets))):
print(tweets[i].display())
if __name__ == "__main__":
main()
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