Processing lists read from a file in Python - python

I am a Python 2.7 (and programming) beginner. Also, this is my first question on SO.
I am currently building a little shopping cart application. I am storing shopping cart values in a txt file. If the user running the script has already a cart saved in the txt file from a previous session, I want the program to make the offer to continue with those items in cart.
Here is what I have so far:
my_file = open("cart.txt", "r")
match = re.findall(r'%s' % enter_name, my_file.read())
my_file.close()
#using a regular expression here to find the person's cart by name
#in cart.txt.
if match:
print "Hello %s, welcome back." % enter_name
print "Do you want to use your previous Shopping Cart?"
continue_cart = raw_input("Type 'yes' or 'no' ")
if continue_cart == "yes":
with open("cart.txt", "r") as my_file:
for line in my_file:
line_list = line.split()
print line_list
#to be continued
The final print statement is basically only a placeholder and a way for me to see what the happens. I am kinda stuck there. The code with the for loop at the end basically produces various lines with a list each. Like this
['Martin']
['Milk', '2']
['Apple', '4']
What I want to do is to "access" the values representing products & quantity in order to then add them to the shopping card class. But how to process this list in order to be able to access the values?
Any help is appreciated. Thanks.

As e4c5 said by not utilizing more advanced concepts (a database, or just using a simple json or pickle) you are making it much harder for yourself.
If you want to use only plain text files directly to store and load values not only it's much harder to write the code (honestly, i've been programming for years and I still would not be confident I got that right!) but also for everyone (including yourself in the future) to read the code. And maintainability is really - from experience - the holly grail of programming. That's why we use python after all!
That said, I understand, you are not trying not build a perfect solution but to learn programming!
That said, your cart.txt probably looks something like this:
Martin
Milk 2
Apple 4
Eva
Milk 1
Then your for loop would look like this (for example, but as I said, this is not a right approach and I it is very fragile and buggy!):
enter_name_found = False
cart_items = {}
for line in my_file:
line_list = line.split()
if len(line_list) == 1:
if line_list[0] == enter_name:
enter_name_found = True
else:
if enter_name_found:
break
else:
if enter_name_found:
cart_items[line_list[0]] = line_list[1]
print(cart_items)
EDIT:
To demonstrate how much simpler this all is using a database:
Here is a full example to save a cart:
import shelve
cart = shelve.open("cart.dat")
cart["Martin"] = {"Apple": 5, "Milk": 2}
cart["Eva"] = {"Milk": 1, "Cat": 4}
cart.close()
And full example to load the cart from the DB:
import shelve
cart = shelve.open("cart.dat")
print(cart["Martin"])
print(cart["Eva"])

Related

Find IP address which occurs most frequent and count the number of times that it appears

Hi all First time having to look for assistance but i am sort of at a brick wall for now. i have been learning python since August and i have been giving a challenge to complete for the end of Novemeber and i hope that there could be some help in making my code works. My task requires to find an ip address which occurs most frequent and count the number of times it appears also this information must be displayed to the user i have been giving 4 files .txt that have the ips. I am also required to make use of non trivial data structures and built in python sorting and/or searching functionalities, make use of functions, parameter passing and return values in the program. Below is a sample data structure they have recommended that i use: -
`enter code here`
def analyse_logs(parameter):
# Your Code Hear
return something
def extract_ip(parameter):
# Your Code Hear
return something
def find_most_frequent(parameter):
# Your Code Hear
return something
# Test Program
def main():
# Your Code Hear
# Call Test Program
main()
And below hear is what i have came up with and the code is completley differant from the sample that has been provided but what i have done dosnt give me output straight back instead creats a new text file which has been sorted but now what i am looking for: -
enter code here
def sorting(filename):
infile = open(filename)
ip_addr = []
for line in infile:
temp = line.split()
for i in temp:
ip_addr.append(i)
infile.close()
ip_addr.sort()
outfile = open("result.txt", "w")
for i in ip_addr:
outfile.writelines(i)
outfile.writelines(" ")
outfile.close()
sorting("sample_log_1.txt")e here
The code that i have created has sorted everything thats in the .txt file and outputs the most frequent that has been used all the way to the lest frequent. All i am look for is for an algorithim that can sort through the .txt file, find the IP address thats more frequent then print that ip out and how many times it appears. I hope i have provided everything and i am sure this is probally somthing very basic but i just cant get my head round it.
You should keep the number of times the IP addresses are repeated in a variable. You can use dictionary.
ip_count_dict = {"IP1": repeat_count, "IP2": repeat_count}
When first time you find a IP in your list set repeat_count 1 and after that if you find same ip again just increase counter.
For example,
ip_count_dict = {}
ip_list = ['1.1.1.1','1.1.1.2','1.1.1.3','1.1.1.1']
#Loop and count ips
#Final version of ip_count_dict {'1.1.1.1':2 , '1.1.1.2':1, '1.1.1.3':1}
With this dictionary you can store all ips and sort by their value.
P.S.: Dictionary keeps key,value pairs you can search "sort dictionary by value" after all counting thing done.

My program is not producing an output, why is this?

I recently just asked a question on SO regarding on how to turn a text file into a dictionary on Python, it worked until I made a slight adjustment to the code as I want to compare the key to a word in a string, and if the key was the same as the word, it would print the corresponding value, however no output is printed, why is this?
def answerInput():
print("Hello, how may I help you with your mobile device")
a = input("Please enter your query below\n")
return a
def solution(answer):
string = answer
my_dict = {}
with open("Dictionary.txt") as f:
for line in f:
key, value = line.strip("\n").split(maxsplit=1)
my_dict[key] = value
for word in string.split():
if word == my_dict[key]:
print(value)
process = 0
answer = answerInput()
solution(answer)
If anyone it helps, my text file is as goes:
battery Have you tried charging your phone? You may need to replace your battery.
dead Have you tried charging your phone? You may need to replace your battery.
sound Your volume may be on 0 or your speakers may be broken, try using earphones.
screen Your screen may be dead, you may need a replacement.
touchID You may need to wipe the fingerprint scanner, try again.
microphone You may need to replace your microphone.
Read the file into my_dict dictionary first, then do lookups into it (your current code as posted reads the file as it does the lookups). Also, compare the words of the user's answer to the keys, not values of the my_dict dictionary (as your code does).
All of this also means that the code should have 3 parts, perhaps something similar to the solution below.
def read_dictionary(in_file):
my_dict = {}
with open(in_file) as f:
for line in f:
key, value = line.strip('\n').split(maxsplit=1)
my_dict[key] = value
return my_dict
def read_query():
print('Hello, how may I help you with your mobile device')
return input('Please enter your query below\n').strip('\n')
def solve(query, my_dict):
for word in query.split():
if word in my_dict:
print(my_dict[word])
return
return
my_dict = read_dictionary('Dictionary.txt')
query = read_query()
solve(query, my_dict)
you're trying to compare the variable 'answer' to the variable 'key', not the value stored in my_dict[key].
also, I'd suggest you use .lower() such as: if answer.lower() == key
so you'd be able to process user responses even if they are in upper case letters
I'm not sure if this is the way you want it to work and configparser usage is a little different but I kinda like the way it can work here.
import configparser
config = configparser.ConfigParser()
config.read("conf.ini", encoding="utf-8")
def answerInput():
print("Hello, how may I help you with your mobile device")
a = input("Please enter your query below\n")
return a
answer = answerInput()
print(config.get("Answers", answer))
conf.ini file in the same directory:
[Answers]
battery = Have you tried charging your phone? You may need to replace your battery.
dead = Have you tried charging your phone? You may need to replace your battery.
sound = Your volume may be on 0 or your speakers may be broken, try using earphones.
screen = Your screen may be dead, you may need a replacement.
touchID = You may need to wipe the fingerprint scanner, try again.
microphone = You may need to replace your microphone.
This is obviously depending if you already have a huge list of those key value pairs or you are gonna be creating ones. If you are creating ones, this might be a nice strucured way to do it.

Python overwriting variable in script 1 with user input from script2

I've been struggling with this for several days now, and I cant find any answers that actually relate to what I'm trying to do, at least none that I can find.
I am trying to create a basic system for keeping track of my finances (i.e. cash, whats in the bank, etc). I have two scripts: display.py and edit.py.
The idea is that I can easily pull up display.py and see how much I have and where it is, and use edit.py to change the amounts shown in display.py, without having to open Vi or entering the numbers every time i run display.py.
In theory, edit.py would take user input, and then overwrite the value in display with that new input, so that display is independent of edit and saves those values
display.py:
cash1 = "5.14"
bank1 = "none"
print "you have", cash1, "in your pocket"
print ""
print ""you have", bank1, "in the bank"
and using this in edit.py
f = open("display.py", "r")
contents = f.readlines()
f.close()
cashinput1 = "cash1"
cashinput2 = raw_input("enter the new coin amount: ")
cashtransfer = ("=".join((cashinput1,cashinput2,)))
contents.insert(5, cashtransfer)
f = open("display.py", "w")
contents = "".join(contents)
f.write(contents)
f.close()
I know edit.py isn't very clean, but the problem is that it's adding the input to the end of a line, pushing it to the next one. The goal is overwrite cash1, not add another. I've tried simply importing, but that doesn't work as the changes aren't saved.
tl;dr How do I overwrite a variable in one script with user input from another script?
I'm using Python 2.7.12
thanks in advance.
EDIT: Sqlite3 looks designed for this type of thing, so this question is answered. Not sure how to close this without any answers though.
As I've been pointed toward Sqlite3, I will use that. Thanks again, question answered :)

Building a ranking list in Python: how to assign scores to contestants?

(I posted this on the wrong section of Stackexchange before, sorry)
I'm working on a assignment which is way above my head. I've tried for days on end figuring out how to do this, but I just can't get it right...
I have to make a ranking list in which I can enter a user, alter the users score, register if he/she payed and display all users in sequence of who has the most score.
The first part I got to work with CSV, I've put only the basic part in here to save space. The menu and import csv have been done: (I had to translate a lot from my native language, sorry if there is a mistake, I know it's a bad habit).
more = True
while more:
print("-" * 40)
firstname = raw_input("What is the first name of the user?: ")
with open("user.txt", "a") as scoreFile:
scoreWrite = csv.writer(scoreFile)
scoreWrite.writerow([firstname, "0", "no"])
scoreFile.close()
mr_dnr = raw_input("Need to enter more people? If so, enter 'yes' \n")
more = mr_dnr in "yes \n"
This way I can enter the name. Now I need a second part (other option in the menu of course) to:
let the user enter the name of the person
after that enter the (new) score of that person.
So it needs to alter the second value in any entry in the csv file ("0") to something the user enters without erasing the name already in the csv file.
Is this even possible? A kind user suggested using SQlite3, but this basic CSV stuff is already stretching it far over my capabilities...
Your friend is right that SQlite3 would be a much better approach to this. If this is stretching your knowledge too far, I suggest having a directory called users and having one file per user. Use JSON (or pickle) to write the user information and overwrite the entire file each time you need to update it.

Looping through python code

I have a python script which searches a web page for information. currently I add the search term as a parameter when i run my program 'myscript.py searchterm'.
What I would like to do is to have a file with my search terms in, get my script to loop through each one in turn on its own.
so I would populate my list from a file like this....
with open('mylist.txt', 'r') as f:
searchterms = f.readlines()
I already have my code which looks something like this...just to give you an idea of layout...
counter = 0
try:
while counter <10:
#do some other stuff here
counter=counter+10
except IOError:
print "No result found!"+""
I need to wrap this in another loop to do this for every item in my list and I'm failing.
I know I need to reset the counter if it gets to 10, move onto my next list item and loop through the above but I don't know how.
I find the python docs difficult to understand and I would appreciate a little help.
TIA
If you have a list of search terms, you can easily loop through them and pass them to your existing loop like:
for searchterm in searchterms:
counter = 0
try:
while counter <10:
#do some other stuff here with searchterm
counter=counter+10
except IOError:
print "No result found!"+""
Be sure that your counter correctly resets at the beginning of each search term's loop.

Categories

Resources