If there is no answer I want it to pass. I don't want it to write in an excel table. If there is no answer, I want you to move on to the next question.
I'm sorry I don't know much English. If there is an answer, do not write anything in the excel table. skip to the next question
from encodings import utf_8
import people_also_ask as paa
from fake_useragent import UserAgent
ua = UserAgent()
while True:
input("Please make sure the queries are in \\query.txt file.\npress Enter to continue...")
try:
query_file = open("query.txt","r")
queries = query_file.readlines()
query_file.close()
break
except:
print("Error with the query.txt file...")
for query in queries:
res_file = open("result.csv","a",encoding="utf_8")
try:
query = query.replace("\n","")
except:
pass
print(f'Searching for "{query}"')
questions = paa.get_related_questions(query, 14)
questions.insert(0,query)
print("\n________________________\n")
main_q = True
for i in questions:
i = i.split('?')[0]
try:
answer = str(paa.get_answer(i)['response'])
if answer[-1].isdigit():
answer = answer[:-11]
print(f"Question:{i}?")
except Exception as e:
print(e)
print(f"Answer:{answer}")
if main_q:
a = ""
b = ""
main_q = False
else:
a = "<h2>"
b = "</h2>"
res_file.writelines(str(f'{a}{i}?{b},"<p>{answer}</p>",'))
print("______________________")
print("______________________")
res_file.writelines("\n")
res_file.close()
print("\nSearch Complete.")
input("Press any key to Exit!")
If you want to detect that the input is blank, then just add a condition in your code.
inputvar = input("Enter string: ")
if inputvar == "":
print("Blank input entered!")
else:
print(inputvar)
But just whatever you do, do not enter a .replace("", "None") code in your project because this can cause a serious error: Even if you enter an answer the input variable, it will enter None after each letter/symbol you enter!
Code:
from encodings import utf_8
import people_also_ask as paa
from fake_useragent import UserAgent
ua = UserAgent()
while True:
input("Please make sure the queries are in \\query.txt file.\npress Enter to continue...")
try:
query_file = open("query.txt", "r")
queries = query_file.readlines()
query_file.close()
break
except:
print("Error with the query.txt file...")
for query in queries:
res_file = open("result.csv", "a", encoding="utf_8")
try:
if query == "":
query = query.replace("\n", "")
else:
pass
except:
pass
print(f'Searching for "{query}"')
questions = paa.get_related_questions(query, 14)
questions.insert(0, query)
print("\n________________________\n")
main_q = True
for i in questions:
i = i.split('?')[0]
answer = str(paa.get_answer(i)['response'])
try:
if answer[-1].isdigit():
answer = answer[:-11]
print(f"Question:{i}?")
except Exception as e:
print(e)
print(f"Answer:{answer}")
if main_q:
a = ""
b = ""
main_q = False
else:
a = "<h2>"
b = "</h2>"
res_file.writelines(str(f'{a}{i}?{b},"<p>{answer}</p>",'))
print("______________________")
print("______________________")
res_file.writelines("\n")
res_file.close()
print("\nSearch Complete.")
input("Press any key to Exit!")
Related
So i have this college python project that asks me to make a program to manage an inventory, my question basically is that whenever I try to convert the price and the quantity again to floats this exception rase, so how can I convert them so I can make further process on them?
note that I tried to use .strip but it didn't work
this is the error:
float_price = float(i)
ValueError: could not convert string to float: '.'
this is the code that I have issues with:
from tabulate import tabulate
def read_data():
file = open("inventory.txt", "r")
list_of_lists = []
for line in file:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
updated_list = list_of_lists[1:]
file.close()
return updated_list
def list_data():
updated_list = read_data()
index = 0
price = 0
quantity = 0
j = 0
while j < len(updated_list):
for i in updated_list[1][4]:
float_price = float(i)
price += float_price
print(price)
header = ['MAKE', 'MODEL', 'PART ID', 'PART NAME', 'PRICE', 'QUANTITY']
print(tabulate(updated_list, headers=header))
list_data()
this is the code to add data to the file:
def input_parts():
#Taking the parts input from the user
try:
make = input("Enter the make: ")
model = input("Enter the model: ")
part_id = input("Enter part_id: ")
part_name = input("Enter part name: ")
price = float(input("Enter price:QR "))
quantity = int(input("Enter quantity: "))
except ValueError:
print("BOTH PRICE AND QUANTITY CAN NOT BE LETTERS, PLEASE RE-ENTER THE RIGHT DATA")
else:
#transferring both price and quantitiy to strings
price = str(price)
quantity = str(quantity)
list = ['\n' + make,model,part_id,part_name,price,quantity]
return list
#This function is to save the parts information to a file
def add_parts():
#Assignning this sentinal to make the loop repeat if the user didn't want to save
sentinal = True
while sentinal is True:
#Assigning the values of the inputs function to a variable
parts = input_parts()
#Validating user's unput
try:
#Asking the user if he wants to save the information to the file
save = input("Save? (Y/N) or Q to quit ")
except TypeError:
print("YOU CANNOT SAVE WRONG DATA IN THE FILE PLEASE RE-ENTER YOUR DATA")
else:
pass
#A boleen function to import the data to the file if the boleen is true
if save.lower() == 'y':
outfile = open('inventory.txt',"a")
#Validating user's input
try:
#Using a for loop to print the information in the file
for i in parts:
outfile.write(i+ '\t')
except TypeError:
print("YOU CAN NOT SAVE WRONG DATA FILES!!!")
break
else:
pass
outfile.close
print("....Record saved.")
sentinal = False
#Using an elif statment to enable the user to re input his data
elif save.lower() == 'n':
sentinal = True
#Using an elif statment to quit if the user wants to
elif save.lower() == 'q':
break
#Using else statment to tell the user no input a valid choice
else:
print("PLEASE ENTER (Y/N) IF YOU WANT TO SAVE!!!!")
print("YOUR DATA HAS NOT BEEN SAVED")
print("PLEASE RE-ENTER YOUR DATA AND TRY AGAIN.")
sentinal = True
add_parts()
as error message indicates '.' is string and it cannot be converted to float so raises error.. it depends what you want to do with such situation you can use try except as.
from tabulate import tabulate
def read_data():
file = open("inventory.txt", "r")
list_of_lists = []
for line in file:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
updated_list = list_of_lists[1:]
file.close()
return updated_list
def list_data():
updated_list = read_data()
index = 0
price = 0
quantity = 0
j = 0
while j < len(updated_list):
for i in updated_list[1][4]:
try:
float_price = float(i)
price += float_price
except ValueError as e:
print('Value Error')
print(price)
header = ['MAKE', 'MODEL', 'PART ID', 'PART NAME', 'PRICE', 'QUANTITY']
print(tabulate(updated_list, headers=header))
list_data()
Updated selenium script with opensource autoliker, i will post social network, username and password because it hard to understan what happens real life, edited some code scrolls still same result only first post liked.
only thing i want is to click like button on
a.find_element_by_css_selector("span#like-button.btn.btn-default.stat-item")
and keep scroling, each like button has same atribute
social network hiall.app
username -whatl0ol
password - tornike123
trying to update source, will post results
source code
from selenium import webdriver
from selenium.common import exceptions
from selenium.webdriver.chrome.options import Options
class FacebookBot:
def __init__(self,username,password,status_report=False):
self.username = username
self.password = password
self.status_report = status_report
options = Options()
options.add_argument("--disable-notifications")
if self.status_report: print("Opening chromedriver...")
self.wd = webdriver.Chrome(chrome_options=options)
if self.status_report: print("Logging in...")
self.login()
def login(self):
self.wd.get("https://hiall.app")
self.wd.find_element_by_name("username").send_keys(self.username)
self.wd.find_element_by_name("password").send_keys(self.password)
self.wd.find_element_by_css_selector("button.btn.btn-main").click()
def convert_to_int(self,string):
try:
return int(string)
except ValueError:
if string.lower().endswith("k"):
string = string[:-2]
try:
return int(float(string)*1000)
except ValueError:
return int(string)*1000
def get_posts(self):
articles = self.wd.find_elements_by_css_selector("span#like-button.btn.btn-default.stat-item")
data = []
for a in articles:
if a.get_attribute("id").startswith("span#like-button.btn.btn-default.stat-item"):
likeIts = [i.get_attribute("aria-label").split() for i in a.find_elements_by_css_selector("span#like-button.btn.btn-default.stat-item") if i.get_attribute("aria-label")]
likes = {"Like":0,"Love":0,"Haha":0,"Wow":0,"Sad":0,"Angry":0}
likes.update({i[1]: self.convert_to_int(i[0]) for i in likeIts})
try:
button = a.find_element_by_css_selector("span#like-button.btn.btn-default.stat-item")
except exceptions.NoSuchElementException:
continue
data.append({"likes":likes,"button":button,"article":a})
return data
def scroll(self,page_end=100):
find_elem = None
scroll_from = 0
scroll_limit = self.wd.execute_script("return document.body.scrollHeight")
i = 0
while not find_elem:
self.wd.execute_script("window.scrollTo(%d, %d);" % (scroll_from, scroll_from + scroll_limit))
scroll_from += scroll_limit
i += 1
if page_end and i >= page_end:
break
try:
find_elem = self.wd.find_element_by_css_selector("span#like-button.btn.btn-default.stat-item")
find_elem.click()
except exceptions.ElementNotVisibleException:
find_elem = None
except exceptions.NoSuchElementException:
find_elem = None
def automate(self,unlike=False,page_end=100):
if self.status_report: print("Forcing Facebook to load the posts...")
self.scroll(page_end)
if self.status_report: print("Scrolled down %s times" % page_end)
if self.status_report: print("%s posts..." % ("Unliking" if unlike else "Liking"))
self.wd.execute_script("window.scrollTo(0,0);")
posts = self.get_posts()
num = 0
for p in posts:
if p["likes"]["Angry"] == 0 and p["likes"]["Sad"] == 0 and p["likes"]["Like"] >= 5:
article = p["article"]
self.wd.execute_script("arguments[0].scrollIntoView();", article)
button = article.find_element_by_css_selector("span#like-button.btn.btn-default.stat-item")
if true:
#button.get_attribute("aria-pressed") == ("true" if unlike else "false"):
num += 1
self.wd.execute_script("arguments[0].click();",button)
try:
p = article.find_element_by_tag_name("p").get_attribute("innerText")
p = p.replace("\n"," ").encode().decode("utf-8")
except exceptions.NoSuchElementException:
p = ""
except:
p = ""
if self.status_report: print(' - %s "%s"' % ("Unliked" if unlike else "Liked",p))
if self.status_report: print("%s %s posts" % ("Unliked" if unlike else "Liked",num))
def close(self):
self.wd.close()
username = "whatl0ol"
password = "tornike123"
pages = False
while pages is False:
inp = input("How many pages to go through? (default 100, 'all' for whole News Feed): ")
if inp.isdigit():
pages = int(inp)
elif inp == "all":
pages = None
unlike = None
while unlike is None:
inp = input("Do you want to Like (l) or Unlike (u) posts? ")
if inp == "l":
unlike = False
elif inp == "u":
unlike = True
bot = FacebookBot(username,password,status_report=True)
bot.automate(unlike=unlike, page_end=pages)
print("Finished")
print()
input("Return to exit")
try:
bot.close()
except:
pass
I made a program that is supposed to take a list of usernames and passwords from a file. It works perfectly if the files only have one username and password but as soon as I include more than one of them, it does not recognise them at all. Here is the code below.
import easygui as e
import os
upper = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
lower = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
numbers = ["1","2","3","4","5","6","7","8","9","0"]
loginsystem = True
while loginsystem == True:
users = []
file = open("users.secure","r")
reading = True
while reading == True:
tempuser = file.readline()
if tempuser == "":
reading = False
else:
users.append(tempuser)
file.close()
passwords = []
file = open("passwords.secure","r")
reading = True
while reading == True:
temppassword = file.readline()
if temppassword == "":
reading = False
else:
passwords.append(temppassword)
file.close()
loginmsg = "Enter your username and password"
logintitle = "Login"
loginfieldnames = ["Username","Password"]
loginfieldvalues = []
login = True
while login == True:
loginfieldvalues =
e.multpasswordbox(loginmsg,logintitle,loginfieldnames)
while 1:
if loginfieldvalues == None: break
loginerrmsg = ""
for i in range(len(loginfieldnames)):
if loginfieldvalues[i].strip() == "":
loginerrmsg = loginerrmsg + ('"%s" is a required field.\n\n' % loginfieldnames[i])
if loginerrmsg == "": break
loginfieldvalues = e.multpasswordbox(loginerrmsg, logintitle, loginfieldnames, loginfieldvalues)
inputuser = loginfieldvalues[0]
inputpassword = loginfieldvalues[1]
if inputuser not in users:
e.msgbox("Unknown username.",title="Login",ok_button="Try Again")
else:
placement = users.index(inputuser)
if inputpassword != passwords[placement]:
e.msgbox("Invalid password.",title="Login",ok_button="Try Again")
else: login = False
e.msgbox("Welcome, " + inputuser,title="Login System",ok_button="Continue")
basicoptions = ["Logout","Quit"]
running = True
while running == True:
choice = e.buttonbox("What would you like to do?",title="Login System",choices=basicoptions)
if choice == "Quit":
os._exit(0)
else:
running = False
The files just contain the word "admin" and when I add another value, I add it onto the next line using "\nadmin2" when writing to the file.
io.readline() will return the newline. That means if you have only one entry, you're likely getting admin, but with more lines, you're getting admin\n.
Instead you can do:
tempuser = file.readline().strip()
Unrelated to the question, but you can cleanup the code a lot. For example for reading files:
def read_file(path):
with open(path, 'r') as f:
return [line.strip() for line in f]
users = read_file('users.secure')
passwords = read_file('passwords.secure')
I am trying to insert some data into a a database I am making and it will not insert. I literally have used the same insert method on other code and it still seems to work, however this one refuses to. Help!
from Bio import Entrez
from sys import exit
Entrez.email = "A.N.Other#example.com" # Always tell NCBI who you are
sranumber = raw_input("Input SRA number here")
sranumber2= raw_input("re-type SRA number here")
while True:
if sranumber != sranumber2:
print "SRA numbers do not match"
sranumber2 = raw_input("Please re-type sra number to match intitial sra number")
continue
else:
break
print "SRA ID:" + sranumber
#answer = raw_input("Are you sure this is the sra number you wish to use? Type Y/N")
while True:
answer = raw_input("Are you sure this is the sra number you wish to use? Type Y/N")
if answer == "Y":
print "Let's do it!"
break
elif answer == "y":
print "Let's do it!"
break
elif answer == "yes":
print "Let's do it!"
break
elif answer == "YES":
print "Let's do it!"
break
elif answer == "N":
exit()
else:
print "Not a valid answer"
search = Entrez.esearch(term = sranumber, db = "SRA", retmode = "xml")
record = Entrez.read(search, validate = False)
newstuff = record
#print newstuff
for j in record:
if j == "WarningList":
newstuff = record['WarningList']
#print newstuff
poop = newstuff
for item in poop:
if item == "OutputMessage":
poop = poop['OutputMessage']
#print poop
crap = ['Wrong UID' + " " + sranumber]
cool = "'"+crap[0]+"'"
#print cool
continuity = ''
for j in poop:
if j == 'No items found.' or j == cool:
print "[-] This is not a valid SRA identity"
continuity = 'done'
if continuity == 'done':
exit()
print "[+] This is a valid SRA identity"
print "SRA ID:" + sranumber
condition = raw_input("Type in the condition of your ngs_data here")
condition2 = raw_input("re-type the condition of your ngs_data here")
print condition
while True:
if condition != condition2:
print "Conditions do not match!"
condition2 = raw_input("Please retype condition here to match first condition")
else:
break
print "just dropped in to check on what condition my condition was in"
stuff = []
stuff.append(sranumber)
stuff.append(condition)
stuff2 = '+'.join(stuff)
print stuff2
stuff3 = stuff2.split('+')
print stuff3
experiment = [tuple(stuff3)]
print experiment
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
def insert_books(experiment):
query = "INSERT IGNORE INTO organisms(sra#, condition) " \
"VALUES(%s,%s)"
try:
db_config = read_db_config()
conn = MySQLConnection(**db_config)
cursor = conn.cursor()
cursor.executemany(query, experiment)
conn.commit()
except Error as e:
print('Error:', e)
finally:
cursor.close()
conn.close()
def main():
insert_books(experiment)
if __name__ == '__main__':
main()
I ended up just doing it this way and it finally worked. I am unsure why it did not work before but I believe that it had something to do with the formatting of how i typed in the columns.
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
cnx = mysql.connector.connect(user='root',password='*****',database = 'new')
cursor = cnx.cursor()
addstuff= ("INSERT IGNORE INTO experiment (`sra`, `condition`) VALUES(%s,%s)")
cursor.execute(addstuff,stuff3)
cnx.commit()
cursor.close()
cnx.close()
I'm trying to have my input move on when enter is pushed on a line with only spaces or just a blank, it doesn't work though it gives me a value error once before it gives me the proper return, which in turn seems to append an extra value to my array and screws over the entire program.
import math
def getItems():
quitNow = False
while not quitNow:
prepTotal = []
paintTotal = []
priceTotal1 = []
priceTotal1d = []
priceTotal2 = []
priceTotal2d = []
names = []
loopQuit = False
index = 1
while not loopQuit:
ans = raw_input("Enter a Name and press Enter to Continue\nEnter \"Q\" to Quit and get the Full Price: ")
if(ans.lower() != "q"):
innerLoopQuit = False
names.append(ans)
print "\nPlease enter your prep hours for " + names[index-1] + ": "
while not innerLoopQuit:
try:
inp = raw_input()
if(inp == ""):
innerLoopQuit = True
else:
float(inp)
prepTotal.append(float(raw_input()))
except ValueError:
print "Please enter a valid number."
You're calling raw_input() again in your else clause. Also, float(inp) doesn't really do anything if you don't assign it anywhere. prepTotal.append(float(inp)) is what you want to do.