Writing and Editing Files (Python) - python

First of all i would like to apologize since i am a beginner to Python. Anyway I have a Python Program where I can create text files with the general form:
Recipe Name:
Item
Weight
Number of people recipe serves
And what I'm trying to do is to allow the program to be able to retrieve the recipe and have the ingredients recalculated for a different number of people. The program should output the the recipe name, the new number of people and the revised quantities for the new number of people. I am able to retrieve the recipe and output the recipe however i am not sure how to have the ingredients recaculated for a different number of people. This is part of my code:
def modify_recipe():
Choice_Exist = input("\nOkaym it looks like you want to modify a recipe. Please enter the name of this recipe ")
Exist_Recipe = open(Choice_Exist, "r+")
time.sleep(2)
ServRequire = int(input("Please enter how many servings you would like "))

I would recommend splitting your effort into multiple steps, and working on each step (doing research, trying to write the code, asking specific questions) in succession.
1) Look up python's file I/O. 1.a) Try to recreate the examples you find to make sure you understand what each piece of the code does. 1.b) Write your own script that accomplishes just this piece of your desired program, i.e. opens an exist recipe text file or creates a new one.
2) Really use you're own functions in Python particularly with passing your own arguments. What you're trying to make is a perfect example of good "modular programming", were you would right a function that reads an input file, another that writes an output file, another that prompts users for they number they'd like to multiple, and so on.
3) Add a try/except block for user input. If a user enters a non-numeric value, this will allow you to catch that and prompt the user again for a corrected value. Something like:
while True:
servings = raw_input('Please enter the number of servings desired: ')
try:
svgs = int(servings)
break
except ValueError:
print('Please check to make sure you entered a numeric value, with no'
+' letters or words, and a whole integer (no decimals or fractions).')
Or if you want to allow decimals, you could use float() instead of int().
4) [Semi-Advanced] Basic regular expressions (aka "regex") will be very helpful in building out what you're making. It sounds like your input files will have a strict, predictable format, so regex probably isn't necessary. But if you're looking to accept non-standard recipe input files, regex would be a great tool. While it can be a bit hard or confusing skill to learn, but there are a lot of good tutorials and guides. A few I bookmarked in the past are Python Course, Google Developers, and Dive Into Python. And a fantastic tool I strongly recommend while learning to build your own regular expression patterns is RegExr (or one of many similar, like PythonRegex), which show you what parts of your pattern are working or not working and why.
Here's an outline to help get you started:
def read_recipe_default(filename):
# open the file that contains the default ingredients
def parse_recipe(recipe):
# Use your regex to search for amounts here. Some useful basics include
# '\d' for numbers, and looking for keywords like 'cups', 'tbsp', etc.
def get_multiplier():
# prompt user for their multiplier here
def main():
# Call these methods as needed here. This will be the first part
# of your program that runs.
filename = ...
file_contents = read_recipe_file(filename)
# ...
# This last piece is what tells Python to start with the main() function above.
if __name__ == '__main__':
main()
Starting out can be tough, but it's very worth it in the end! Good luck!

I had to edit it a couple times because I use Python 2.7.5, but this should work:
import time
def modify_recipe():
Choice_Exist = input("\nOkay it looks like you want to modify a recipe. Please enter the name of this recipe: ")
with open(Choice_Exist + ".txt", "r+") as f:
content = f.readlines()
data_list = [word.replace("\n","") for word in content]
time.sleep(2)
ServRequire = int(input("Please enter how many servings you would like: "))
print data_list[0]
print data_list[1]
print int(data_list[2])*ServRequire #provided the Weight is in line 3 of txt file
print ServRequire
modify_recipe()

Related

Creating a personal accounting program

I am new to python and may have been overly optimistic about the first project I want to tackle. I want to create a program that will help me allocate my checks(I have a banking app this is just for fun lol). I also want this to be a continuous program so it will check to see if there is a 'SavedData.txt' file and if there is it will present all the starting balances in 3 accounts from the last time it was used. Then continue to ask questions to allocate into said accounts from the new check. However, if the file doesn't exist I want it to create it, ask questions and then save the inputs to be called upon the next time it is run.
Here's what I have:
'If the file does not exist ask this prompt'
month = input("Please enter month: ")
day = input("Please enter the day: ")
year = input("Please enter the year: ")
initial_checking = int((input("What is your initial checking account balance?: ")))
initial_savings = int((input("What is your initial savings account balance?: ")))
initial_fun = int((input("What is your initial fun account balance?: ")))
current_check = int((input("What is your check amount?: ")))
save_cont = int(input("How much would you like to contribute to savings?: "))
fun_cont = int(input("How much would you like to contribute to fun account?: "))
current_check = int((current_check - save_cont) - fun_cont)
print("Remaining check balance is " + str(current_check) + ".")
def main():
while True:
q = input("Would you like to put the rest in checking?(Type Y/N): ")
if q in "yY":
global initial_checking
global initial_savings
global initial_fun
global current_check
initial_checking = int(initial_checking + current_check)
print("Your new checking balance is " + str(initial_checking))
return
elif q in "nN":
print("Error! You must contribute your entire check!")
else:
print("You must enter (y/n).")
return
main()
After this is where I start to have issues. If the file does exist, or if the program has been run before, I want it to read the last input and display "This is your current checking account balance: $" and so on and so forth. I then want the same contribution questions to be asked and added to the current balance amount for each respective account. Doing research I have seen when doing something like 'file1 = open("SavedData.txt", "a+") ' will open and append the file. My issue is figuring out how to set up running the check for the file, opening, reading it, adding to it, or creating it then writing, and saving it.
My apologies if there is redundant information or if it looks extremely sloppy as I said I am very very new and may have been overly optimistic about doing this project. I appreciate your time and responses.
As it is your first project I would suggest learning good design from the start. So try to plan out what you have to do first, what components will be needed and how will they interact (you can use sticky notes or whatever you like but have a plan before you start coding), as it will help you define classes/functions when you will be actually writing code.
So for now you nicely define the things you need to do, so do them one by one testing each step.
As of your question about file manipulation first start by writing function that opens a file and read it, as of now using with statement is good practice instead of manually opening and closing files, you can read more here and here.
Then try to write part of your code that defines what should be added to file (I'm not really sure how checks work so I can't help you here).
And when you know what you want to add create a function that will write to the file, it will be similar to reading so you can again refer to previously mentions links.
Finally if everything above is done you can try to enclose it in a loop that will constantly monitor the file. Probably the best approach would be to use already created library like watchdog but if you want to learn how filesystem works it is fine to create custom solution.
Last tip, try to avoid global variables ;P

How can i create a exam generator program in python 3?

*I'm a newbie to python, I'm currently trying to create some random programs. I came accross this challenge. Would love to see how it can be solved, unfortunately I couldn't make this program.
I understand that we should use the random module and also the file handling functions in python.
If any detail is unclear I can re explain it
Write a program, which will help the user to generate exam tickets.
there are 2 files given . 1) with the exercises(exercises.txt):
it contains 30 exercises, each are already written on a new line.
2) we are given the students.txt file. Each line has a full name of a student. The program should allow the user to input the number of exercises which should be generated for the student. The new created ticket should have the students name with .txt file extension. The number must not exceed 30 exercises, if it does we should give them a new try to input the correct number. The exercises should be shuffled(randomized) .
import random
def logic():
number_input = int(input('sheiyvanet cifri'))
students_file = open('students.txt', 'r', encoding='utf8')
exercises_file = open('exercises.txt', 'r', encoding='utf8')
new_ticket_file = open('newTicket.txt', 'w')
while True:
if(number_input < 30):
new_ticket_file.write(str(random.shuffle(exercises_file.readlines())))
new_ticket_file.close()
break
else :
continue
logic()
Please do not simply provide a question and ask for it to be solved. Instead, show your current work and specify what is wrong with it.
Show examples of the text files, as in a few lines from each so that all viewers can properly understand it.
A good starting step is to write a piece of code that does only one thing. Eg:
Input a number.
The number must not exceed 30 exercises, if it does we should give them a new try to input the correct number.
Then write one that achieves a different part of your question. Try connecting these pieces. If it blows up or you really can't work it out, post a new question with the stuff you made and ask for help.

How do I choose the position of the cursor when a user is inputting information in python?

Sorry If my code seems off, this is my first time asking here and I am somewhat new to python.
I want a user to give me the number of sets and reps for a workout.
Here is my code below:
print("Please enter the number of sets you would like to do followed by the number of reps. ")
sets, reps = input("Pushup- \n\t" + "Sets: " + "Reps: ").split()
So when I run this, naturally the cursor will be flashing at the end of "reps:" however what I want it to do is so that when I run it, the cursor will flash after "sets:" and when the user hits the space key, it will move all the way over to after "reps:".
I would recommend just having it as two inputs:
sets = input("Pushup-Sets: ")
reps = input("Pushup-Reps: ")
Is there a particular reason you need it done in one line?
Why don't you try doing something like this:
print("Please enter the number of sets you would like to do followed by the
number of reps.")
print("Pushup-")
sets = input("Sets:")
reps = input("Reps:")
It uses the return button instead of the spacebar, hope it helps!
As others have suggested, having it as two separate inputs will be much easier.
If you do want to make a text-based app which does it the way you've described, the library you're looking for is called "curses" (see: howto, reference).
However, it seems like a bit of an anachronism; for a quick app, separate inputs are much easier, and for a user-friendly app you'll probably want a graphical interface (or web) rather than a text-based one.

how to make a program ignore everything but the key word in users input?

datadict = {}#open the file
with open('phoneproblemquery.txt') as file:
for line in file:
problem, answer = line.split('-')
problems = problem.strip().split(' ')
for item in problems:
datadict[item] = answer
user_problem = input('What is the problem?:')
print(datadict[user_problem])
The text-file contains something like this:
screen - replace screen.
if I were to run this program and enter in 'screen' the program will respond 'replace screen'. but, if I were to enter something like 'the screen'(not just 'screen' alone) the program will give a 'keyError' and won't work.
what would I need to do to if the user enters 'the screen' (instead of just 'screen') for the program to provide an output 'replace screen'. would I need to put the users answer into arrays? if so how?
Thanks!
update: 'the screen' was just an example. The user can enter in any
form of way i.e 'screen is...' the keyword is screen. I would want
the program to identify the key word from the users input and get
the response 'replace screen'. ... ;( desperate for an answer...
You want the program to pick keywords out of the user input and look for them in datadict. The difficulty with that is picking out keywords. A simple approach is to have regular expressions rather than simple keywords as the keys of your lookup dictionary. You will of course have to do the matching yourself: the dictionary lookup process won't do it for you.
import re
datadict = {}
#open the file
with open(r'phoneproblemquery.txt') as file:
for line in file:
problem, answer = line.split('-')
problems = problem.strip().split(' ')
for item in problems:
datadict[re.compile(fr'{item}', re.IGNORECASE)] = answer
user_problem = input('What is the problem?:')
for regex, diagnosis in datadict.items():
if regex.search(user_problem):
print (diagnosis)
This will work, but in a more sophisticated implementation it might be better to put the regular expressions in the input data, rather than constructing them at runtime like I have done here. You are already allowing for something of the sort by having a space-delimited list if keywords in your input data. If you had regular expressions in the input instead, the same would apply, only instead of, say
keyboard kybd - replace keyboard
you would have
keyboard|kybd - replace keyboard
and in that event maybe a hyphen would not be the best delimiter. A carriage return might be better, since that can never appear in the input.

Python - Searching a dictionary for strings

Basically, I have a troubleshooting program, which, I want the user to enter their input. Then, I take this input and split the words into separate strings. After that, I want to create a dictionary from the contents of a .CSV file, with the key as recognisable keywords and the second column as solutions. Finally, I want to check if any of the strings from the split users input are in the dictionary key, print the solution.
However, the problem I am facing is that I can do what I have stated above, however, it loops through and if my input was 'My phone is wet', and 'wet' was a recognisable keyword, it would go through and say 'Not recognised', 'Not recognised', 'Not recognised', then finally it would print the solution. It says not recognised so many times because the strings 'My', 'phone' and 'is' are not recognised.
So how do I test if a users split input is in my dictionary without it outputting 'Not recognised' etc..
Sorry if this was unclear, I'm quite confused by the whole matter.
Code:
import csv, easygui as eg
KeywordsCSV = dict(csv.reader(open('Keywords and Solutions.csv')))
Problem = eg.enterbox('Please enter your problem: ', 'Troubleshooting').lower().split()
for Problems, Solutions in (KeywordsCSV.items()):
pass
Note, I have the pass there, because this is the part I need help on.
My CSV file consists of:
problemKeyword | solution
For example;
wet Put the phone in a bowl of rice.
Your code reads like some ugly code golf. Let's clean it up before we look at how to solve the problem
import easygui as eg
import csv
# # KeywordsCSV = dict(csv.reader(open('Keywords and Solutions.csv')))
# why are you nesting THREE function calls? That's awful. Don't do that.
# KeywordsCSV should be named something different, too. `problems` is probably fine.
with open("Keywords and Solutions.csv") as f:
reader = csv.reader(f)
problems = dict(reader)
problem = eg.enterbox('Please enter your problem: ', 'Troubleshooting').lower().split()
# this one's not bad, but I lowercased your `Problem` because capital-case
# words are idiomatically class names. Chaining this many functions together isn't
# ideal, but for this one-shot case it's not awful.
Let's break a second here and notice that I changed something on literally every line of your code. Take time to familiarize yourself with PEP8 when you can! It will drastically improve any code you write in Python.
Anyway, once you've got a problems dict, and a problem that should be a KEY in that dict, you can do:
if problem in problems:
solution = problems[problem]
or even using the default return of dict.get:
solution = problems.get(problem)
# if KeyError: solution is None
If you wanted to loop this, you could do something like:
while True:
problem = eg.enterbox(...) # as above
solution = problems.get(problem)
if solution is None:
# invalid problem, warn the user
else:
# display the solution? Do whatever it is you're doing with it and...
break
Just have a boolean and an if after the loop that only runs if none of the words in the sentence were recognized.
I think you might be able to use something like:
for word in Problem:
if KeywordsCSV.has_key(word):
KeywordsCSV.get(word)
or the list comprehension:
[KeywordsCSV.get(word) for word in Problem if KeywordsCSV.has_key(word)]

Categories