How To Save The Replace - Python - python

This is what I am using. It runs everytime the user enters something, and it will replace part of the string, but on the second repeat it goes back to how it was eg
first run of it:
t3st
second run:
te5t
I want both of them to stay so after it would be t35t
if ((letterPair) in (allPairs)):
print ("Correct")
iReplace = open("textfile.txt")
iReplace = iReplace.read()
iReplace = iReplace.replace((letterPair[1]),(letterPair[0]))
print (iReplace)
options()
else:
print ("Incorrect letter pairing")
options()

These two lines need to be moved outside of whatever loop you're using to process input:
iReplace = open("textfile.txt")
iReplace = iReplace.read()
As your code stands now, you are re-reading the original string from textfile.txt every time the user presses a key, and then assigning it to iReplace.
You haven't pasted enough code in to be sure, but I assume there is some sort of loop around the code you posted. Put those lines outside of that.

Related

How would I save the data to a .csv file

I have made a program based on a maths quiz and have saved the data of the files to a .txt file. If I wanted to save the files in a .csv file would i just chnage .txt to .csv? Here is my code :
import time
import math
import random#I am using this to allow me to randomly pick the symbol operation and to randomly generate numbers
print("Title:Arithmetic Quiz")#Tells the user what the program is.
print("*************************************************************")#This is a line to make the presentation clearer to the user.
#The code below shows the user an introduction of what the program is about.
print("This program will ask you to complete the arithmetic quiz.")
print("The program has 10 questions. You will recieve feedback after.")
print("____________________________________________________________")
#The line above prints a line across the page.
while True:#This creates an infinity loop
UserName = input("What is your name?:")#Ask the user for there name.
if not UserName.isalpha():#This is used to check if the user name is anything else apart from alphabetical letters.
print("Error!Please enter your name using letters. ") #warning if wrong if wrong input given
continue#Continues with the code when correct input given.
else:#It breaks out of the while loop and proceeds with the quiz
break
ClassSelection= input("Please enter what Class you are in?:1, 2 or 3")
ClassChosen=0
while ClassChosen==0:
if ClassSelection=="1":
ClassChosen=1
elif ClassSelection=="2":
ClassChosen=1
elif ClassSelection=="3":
ClassChosen=1
else:
print("You must write 1, 2, or 3.")
ClassSelection=input("Enter the class you are in")
print(UserName," welcome to the Arithmetic Quiz.")#Welcomes the user to the quiz.
print("____________________________________________")
print("The quiz will begin in 3 seconds")
time.sleep(2)
for i in range(0,3):# range between
print (3 - i)#counts down by one
time.sleep(1)#Delays for 1 second
print("Begin!")
print("*****************************************")
RecentStudent= [0,0,0]#This is a list with dummy values. The use of this is to save the last three score of the user.
def MathsQuiz():#I have used a function to make my code more efficient.
score=0#No questions have been answered correctly yet so score is set to zero
for questionNum in range(10):#I have used this to allow me to set my Parameters.
Num1= random.randint (1, 10)#Generates a random number between 1 and 10 for Num1.
Num2= random.randint (1, 10)#Generates a random number between 1 and 10 for Num2
Symbol = ["+","-","*"]#These are my operators used for the arithmetic of Num1 and Num2.
Operation = random.choice(Symbol)#This will randomly choose a operating symbol for a question
RealAnswer= int(eval(str(Num1)+Operation+str(Num2)))#This is used to work out the answer for the question.The evaluate is used to interpret the code as a str and calculate an answer.
#It will store the value of the Answer and call it when it is needed.
print("Please give an answer for:", Num1, Operation, Num2)#This is what makes the question and outputs it to the user by using the random functions.
UserAnswer = int(input("Enter your answer here:"))#This asks the user to enter their anser to the question.
if UserAnswer == RealAnswer:#This checks if the answer from the user is the same as the real answer.
score = score + 1#If the user gets the question right 1 should be added to the score.
print("You are correct! :D")#The program will congratulate the user.
print("_______________________________________________")
else:#If the users answer is not the same as the real answer then it will print a wrong message.
print("You are incorrect! :( ")#This tells the user that they got the question incorrect and tells the user the real answer.
print("The answer was", RealAnswer)
print("________________________________________________")#This will be used to split the quiz.
print()#This is used to format the quiz.
print("__________________________________________________")
print("Thank you for completing the quiz!")
print("Your Score is loading")
import time
time.sleep(2)
print(UserName,"In this test you achieved",score,"/10")#This tells the user the score they achieved in the maths test.
print()#This is used to format the code
del RecentStudent[0]
RecentStudent.append(score)
print("Your three most recent scores are:",RecentStudent)
print("********************************************************")
def Resit1():#This function is used to easily call place of the program such as in this case when resitting.
Resit1=input("Do you want to resit the test? Yes or No?:")#Asks the user if they would like to resit
#The variable will let user input whether they want to do the quiz again.
if Resit1== "Yes" or Resit1=="yes":# Checks the input of the user to the resit question
MathsQuiz()#This is used to call the quiz which will restart the quiz and allow them to retake the quiz.
#It tells the user that they are finished
def Resit2():#This function is used to easily call place of the program such as in this case when resitting.
Resit2=input("Do you want to resit the test? Yes or No?:")#Asks the user if they would like to resit
#The variable will let user input whether they want to do the quiz again.
if Resit2== "Yes" or Resit2=="yes":# Checks the input of the user to the resit question
MathsQuiz()#This is used to call the quiz which will restart the quiz and allow them to retake the quiz.
print("Quiz Finished")#It tells the user that they are finished
MathsQuiz()#This will call the first function that has been set in the program.
Resit1()#This will call the Resit1 function when it is needed by the program.
Resit2()#This will call the Resit2 function when it is needed by the program.
if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
Class1 = []#class1 list is created and is empty.
Class1.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class1.append(UserName)#The name variable is appended as the second item.
Class1.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class1.append(RecentStudent)#The score variable is appended as the last item.
file = open("Class1Scores.txt", 'a')#File opened called classAScores.
#It is a text file because I added ".txt"
#I used the mode 'a' because this allows me to append things to the file.
file.write(str(Class1))#Allows me to write the classA list onto the file.
#Because the mode is append, it enables me to append a whole list to the file.
#the str() makes sure the list is interpreted as code as code can be appended.
#The list in its raw form will not append to the file.
file.write("\n")#Ensures the next pupils data is recorded on the row below.
file.close()#Closes the file so everything is saved.
elif ClassSelection=="2":#used to identify whether the ClassSelection is equal to 1.
Class2=[]#classA list is created and is empty.
Class2.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class2.append(UserName)#The name variable is appended as the second item.
Class2.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class2.append(RecentStudent)#The score variable is appended as the last item.
file = open("Class2Scores.txt", 'a')#File opened called classAScores.
#It is a text file because I added ".txt"
#I used the mode 'a' because this allows me to append things to the file.
file.write(str(Class2))#Allows me to write the classA list onto the file.
#Because the mode is append, it enables me to append a whole list to the file.
#the str() makes sure the list is interpreted as code as code can be appended.
#The list in its raw form will not append to the file.
file.write("\n")#Ensures the next pupils data is recorded on the row below.
file.close()#Closes the file so everything is saved.if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
elif ClassSelection==3:
Class3 = []#classA list is created and is empty.
Class3.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class3.append(UserName)#The name variable is appended as the second item.
Class3.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class3.append(RecentStudent)#The score variable is appended as the last item.
file = open("Class3Scores.txt", 'a')#File opened called class3Scores.
#It is a text file because I added ".txt"
#I used the mode 'a' because this allows me to append things to the file.
file.write(str(Class3))#Allows me to write the class3 list onto the file.
#Because the mode is append, it enables me to append a whole list to the file.
#the str() makes sure the list is interpreted as code as code can be appended.
#The list in its raw form will not append to the file.
file.write("\n")#Ensures the next pupils data is recorded on the row below.
file.close()#Closes the file so everything is saved.
This is my code would I need to change the bottom of the code to save the files in a .csv file. I tried doing a different method, but never got anywhere .
I suggest using the csv module. I've adapted your code to use it (there are a lot of ways you could make your life easier with your code, but let's focus on one issue at a time):
import csv
if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
Class1 = []#class1 list is created and is empty.
Class1.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class1.append(UserName)#The name variable is appended as the second item.
Class1.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class1.append(RecentStudent)#The score variable is appended as the last item.
with open('Class1Scores.csv', 'wb') as file:
writer = csv.writer(file)
writer.writerow(str(Class1))
writer.writerow("\n")
Gentle into to the csv module
Because we're using the with keyword, there is no need to call file.close()
For a more advanced way of doing this, you could use pandas to_csv
Looks like your Class1 is simply a list. Then you can say file.write(",".join(Class1)). But a more robust method is to use the csv module - https://docs.python.org/2/library/csv.html

Python comparison of previous data

I have a program that asks the user for raw input and then displays it. What I want to do is this:
If the user enters data that was different from the previous data entered, then update the data, else do nothing.
So all I'm doing is checking whether the data the user enters is the same as the one they entered before but I would like to know how I go about doing this in Python.
The natural way to do this is with a data structure that guarantees that its elements are unique. For instance, try defining a set and adding any new user input to it. If you try to add a string that's already in the set, it will do nothing.
record = set()
while True: # just an example; you'll need to end the loop somehow
message = raw_input('give me data! ')
record.add(message)
print record
Here is a simple way to do it:
user_input = raw_input('enter an input\n')
user_input2 = raw_input('confirm your input\n')
if user_input != user_input2:
print 'updating...'
user_input = user_input2
print 'Input is: {}'.format(user_input)
If you need to split up a string of input, see the documentation for str.split and other handy built in functions:
https://docs.python.org/2/library/stdtypes.html#str.split

Checking to see whether the users input is correct with the correct version

OK, so what my program is all about is that the user has to solve a coded puzzle which gets read in from an external file. The user then guesses what letter matches up with the symbol in the coded puzzle and they can then add this to a list of clues.
One of the options in my program allows the user to check whether the clues they have entered are correct with the solved version. The solved version is read in from an external file and this is what needs to get checked with the list of clues.
So far I have a basic piece of code but what keeps on happening is that the output I get is that " You scored 0 out of 10" even though some of the pairings I have entered are correct.
My code so far for this section of code is this...
def check_clues():
count = 0
# TRIES TO OPEN FILE SOLVED.TXT
try:
with open('solved.txt') as r:
# READS THROUGH ALL THE LINES IN SOLVED.TXT
solved = r.readlines()
# WILL DISPLAY AN ERROR MESSAGE IF SOLVED.TXT IS NOT FOUND
except:
print("Error finding file")
# WILL TRY AND OPEN THE FILE 'clues.txt'
try:
with open('clues.txt') as r:
clues = r.readlines()
except:
print("Error finding ")
# GOES THROUGH BOTH THE USERS CLUES AND SOLVED.TXT TO SEE HOW MANY CLUES ARE THE SAME
for clue in clues:
if clue in solved:
count += 1
# Prints the amount of clues the user got right out of 10
print('You got:', count, 'correct!')
Below is what is in the solved.txt file:
ACQUIRED
ALMANAC
INSULT
JOKE
HYMN
GAZELLE
AMAZON
EYEBROWS
AFFIX
VELLUM
Below is what is in clues.txt
A#
M*
N%
However please note clues.txt is the list which the user can add to. So if the user decides to enter S and &, this will add to the clues.txt as S&
Below is the file words.txt which contains the list of coded words the user has to solve...
#+/084&"
#3*#%#+
8%203:
,1$&
!-*%
.#7&33&
#*#71%
&-&641'2
#))85
9&330*
I had a hand at this, using what you're provided. I believe this is what you're looking for provided you have all the files you listed. Basically I used the words.txt and solved.txt files and created a dictionary mapping all the symbols to their correct letters. Then I used that dictionary to compare each clue to see if they match. This would increment the count and you would get your correct output.
The problem with your original code is that you're simply searching if the clue is inside of the solved text file. For example, you search if your first clue A* is inside of the words text file. Obviously it isn't because there isn't a * in that file. So you need something to baseline/compare it to. Which is why in this case I created a dictionary. I also removed your try/except loops since your program should technically never run if a file is missing. In which case your exceptions will allow the program to keep running even if a file is missing producing multiple error outputs. It should stop if no files are found or be handled specifically, not allow it to keep running as it normally would. If you go that route, I'd also advise only using except WindowsError to avoid catching any other potential exceptions.
def check_clues():
# Dictionary to hold all of the symbol/letter combos
coded_dict = {}
# Go through each symbol/letter combination together
with open("words.txt") as fw, open("solved.txt") as fs:
for fw_line, fs_line in zip(fw, fs):
for fw_symbol, fs_letter in zip(fw_line.strip(), fs_line.strip()):
# Add the symbol/letter combination to the dictionary
coded_dict[fw_symbol] = fs_letter
correct_clues = []
with open("clues.txt") as fc:
for fc_line in fc:
# If the symbol is in the dictionary and the letter matches the symbol
if fc_line[1] in coded_dict and coded_dict[fc_line[1]] == fc_line[0]:
# Add a correct clue to your list
correct_clues.append(fc_line.strip())
print("You got a total of {0} correct: {1}".format(len(correct_clues), ", ".join(correct_clues)))
if __name__ == "__main__":
check_clues()
If you need me to elaborate on anything let me know.

Writing to a File with Python -- ''While not done:" Confusing Me

I have less than a year of programming experience. While learning about reading and writing files I came across this tutorial: http://www.penzilla.net/tutorials/python/fileio/
The tutorial offers the following example as a simple script to create and write to a file:
# Let's create a file and write it to disk.
filename = "test.dat"
# Let's create some data:
done = 0
namelist = []
while not done:
name = raw_input("Enter a name:")
if type(name) == type(""):
namelist.append(name)
else:
break
# Create a file object:
# in "write" mode
FILE = open(filename,"w")
# Write all the lines at once:
FILE.writelines(namelist)
# Alternatively write them one by one:
for name in namelist:
FILE.write(name)
FILE.close()
I copied this code and ran it through a Python 2.7.3 Shell. I am prompted repeatedly to enter strings which are appended to a list that will be written to a file (this makes sense to me). What I don't understand is the condition for exiting the While loop ("While not done:"). I thought this meant that I type done at the prompt to exit the loop and subsequently write the file, but done has no effect. Then I thought that any non-string entered at the prompt should break the loop and write the file. I couldn't get the loop to break at all; for anything I entered at the prompt, I was just prompted again with "Enter a name:".
By removing the While loop and retaining the if/else statement, I got the code to work for a single prompt. Can someone tell me what I am not understanding here? I am guessing it is a fairly simple concept that wasn't explained in the tutorial because it was assumed to be obvious. Since "done" is such a common word, I wasn't able to find any Python specific meanings for it.
I would stop following that tutorial right now. The code isn't Pythonic, it's way too complicated, and it seems to be pretty outdated.
That being said, here's how I'd write that tutorial's code (yes, it does the same thing, but only the right way):
with open('test.dat', 'w') as handle:
while True:
name = raw_input('Enter a name: ')
if not name:
break
handle.write(name + '\n')
done is assigned once on line 3:
done = 0
Therefore, this the while loop will continue to loop as long as done is still "not 0":
while not done:
I.e. it will continue to loop forever, unless it hits a break statement (line 11). Unfortunately, the code is flawed and that will never happen.
If you want to stop when you type 'done', then change the if statement to:
if name == "done":
But, be aware that the literal string done above has nothing to do with the variable done assigned earlier.
It's not your fault. That code provides no way to break out of the loop.
if name == 'end':
break
The code is bad, firstly.
In this case, done is the name of a variable. As written, it will loop forever since there's no way to exit.
You should stop following that tutorial and pick a better one: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

Python program to search for specific strings in hash values (coding help)

Trying to write a code that searches hash values for specific string's (input by user) and returns the hash if searchquery is present in that line.
Doing this to kind of just learn python a bit more, but it could be a real world application used by an HR department to search a .csv resume database for specific words in each resume.
I'd like this program to look through a .csv file that has three entries per line (id#;applicant name;resume text)
I set it up so that it creates a hash, then created a string for the resume text hash entry, and am trying to use the .find() function to return the entire hash for each instance.
What i'd like is if the word "gpa" is used as a search query and it is found in s['resumetext'] for three applicants(rows in .csv file), it prints the id, name, and resume for every row that has it.(All three applicants)
As it is right now, my program prints the first row in the .csv file(print resume['id'], resume['name'], resume['resumetext']) no matter what the searchquery is, whether it's in the resumetext or not.
lastly, are there better ways to doing this, by searching word documents, pdf's and .txt files in a folder for specific words using python (i've just started reading about the re module and am wondering if this may be the route, rather than putting everything in a .csv file.)
def find_details(id2find):
resumes_f=open("resume_data.csv")
for each_line in resumes_f:
s={}
(s['id'], s['name'], s['resumetext']) = each_line.split(";")
resumetext = str(s['resumetext'])
if resumetext.find(id2find):
return(s)
else:
print "No data matches your search query. Please try again"
searchquery = raw_input("please enter your search term")
resume = find_details(searchquery)
if resume:
print resume['id'], resume['name'], resume['resumetext']
The line
resumetext = str(s['resumetext'])
is redundant, because s['resumetext'] is already a string (since it comes as one of the results from a .split call). So, you can merge this line and the next into
if id2find in s['resumetext']: ...
Your following else is misaligned -- with it placed like that, you'll print the message over and over again. You want to place it after the for loop (and the else isn't needed, though it would work), so I'd suggest:
for each_line in resumes_f:
s = dict(zip('id name resumetext'.split(), each_line.split(";"))
if id2find in s['resumetext']:
return(s)
print "No data matches your search query. Please try again"
I've also shown an alternative way to build dict s, although yours is fine too.
What #Justin Peel said. Also to be more pythonic I would say change
if resumetext.find(id2find) != -1: to if id2find in resumetext:
A few more changes: you might want to lower case the comparison and user input so it matches GPA, gpa, Gpa, etc. You can do this by doing searchquery = raw_input("please enter your search term").lower() and resumetext = s['resumetext'].lower(). You'll note I removed the explicit cast around s['resumetext'] as it's not needed.
One change that I recommend for your code is changing
if resumetext.find(id2find):
to
if resumetext.find(id2find) != -1:
because find() returns -1 if id2find wasn't in resumetext. Otherwise, it returns the index where id2find is first found in resumetext, which could be 0. As #Personman commented, this would give you the false positive because -1 is interpreted as True in Python.
I think that problem has something to do with the fact that find_details() only returns the first entry for which the search string is found in resumetext. It might be good to make find_details() into a generator instead and then you could iterate over it and print the found records out one by one.

Categories