I have no idea how to ask users if they want to restart the program again and enter with a new file. I want to ask if the user wants to re-run the program or just terminate it. What's the easiest way to do that? The program is below:
import nltk
from nltk.tokenize import word_tokenize
import re
import os
import sys
from pathlib import Path
data_folder = Path(input("type the path you would like to use: "))
file_to_open = data_folder / input("insert the file you would like to use with its extension: ")
with open(file_to_open) as f:
words = word_tokenize(f.read().lower())
with open ('Fr-dictionary2.txt') as fr:
dic = word_tokenize(fr.read().lower())
l=[ ]
errors=[ ]
out_file=open("newtext.txt","w")
for n,word in enumerate (words):
l.append(word)
if word == "*":
exp = words[n-1] + words[n+1]
print("\nconcatenation error:", exp)
if exp in dic:
l.append(exp)
l.append("$")
errors.append(words[n-1])
errors.append(words[n+1])
else:
continue
for i, w in enumerate(l):
if w == "*":
l.remove(l[i-1])
else:
continue
for i, w in enumerate(l):
if w == "$":
l.remove(l[i+1])
else:
continue
text=' '.join(l)
print('\n\n',text)
e=len(errors)
print('\n',e/2,'WORDS CONCATENATED IN TEXT',errors)
user=input('\nREMOVE * AND $ FROM TEXT? Type "Y" for yes or "N" for no:')
for x in l:
if user=='Y' and x=='*':
l.remove(x)
elif user=='Y' and x=='$':
l.remove(x)
else:
continue
final_text=' '.join(l)
print('\n\n', final_text)
user2=input('\nWrite text to a file? Type "Y" for yes or "N" for no:')
if user2 =='Y':
out_file.write(final_text)
out_file.close()
print('\nText named "newtext.txt" written to a file'
This is the basic structure you are looking for:
def some_function_you_want_to_repeat():
print("Do some stuff")
choice = input("Do you want to do this again? | yes/no")
if choice == 'yes':
some_function_you_want_to_repeat()
some_function_you_want_to_repeat()
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'm trying to write a user input to a word file for my troubleshooting system. However it doesn't write to the file and ends the code. I am trying to make it so that if the user inputs 'no' twice, then it should follow the following code:
if count == 2:
f = open('problems.txt', 'w')
ui = ("What is the problem?")
f.write(ui)
Instead the code ends.
Here's the code:
count = 0
while count != 2:
a = input("Is your phone broken?")
if a == "no":
count = count + 1
if count == 2:
f = open('problems.txt', 'w')
ui = ("What is the problem?")
f.write(ui)
But the code doesn't open the file and write to the file, the program just ends after the user inputs no. I don't understand what I'm doing wrong? Could anyone help me please.
If you are using Python 2.x, use raw_input.
count = 0
while count != 2:
a = raw_input("Is your phone broken?")
print a
if a == "no":
count = count + 1
if count == 2:
f = open('problems.txt', 'w')
ui = ("What is the problem?")
f.write(ui)
Just like the title says I am having trouble adding items to a list for some reason. I am sure it is something simple, but just to make sure.
fnamesfile = open('fnames.txt','w')
global fnames
fnames = ['spanish.db', 'biology.db', 'dictionary.db']
def choose():
global filename
print "\nEXISTING FILES:"
for i in fnames:
print i
print "\nFOR NEW FILE ENTER NEW NAME:"
choice = raw_input('Open: ')
choicedb = "%s.db" % choice
if choicedb in fnames:
filename = shelve.open(choicedb)
else:
choice = raw_input("ARE YOU SURE YOU WANT TO MAKE NEW FILE?[y/n] ")
if choice == 'y':
fnames.append(choicedb)
filename = shelve.open(choicedb)
elif choice == 'n':
choose()
It looks like you need to both import the shelves library and actually make a call to your function.
import shelve
fnames = ['spanish.db', 'biology.db', 'dictionary.db']
def choose():
print fnames # for debugging
global filename
print "\nEXISTING FILES:"
for i in fnames:
print i
print "\nFOR NEW FILE ENTER NEW NAME:"
choice = raw_input('Open: ')
choicedb = "%s.db" % choice
if choicedb in fnames:
filename = shelve.open(choicedb)
else:
choice = raw_input("ARE YOU SURE YOU WANT TO MAKE NEW FILE?[y/n] ")
if choice == 'y':
fnames.append(choicedb)
filename = shelve.open(choicedb)
elif choice == 'n':
choose()
print fnames # for debugging
choose()
The first and last print statements I am leaving in there for you so you can see it working, but you should remove them after you are satisfied that it's working.
I'm very very new to programming and for a school project (50% of my final grade) I had to create a Python program that did roughly this.
I've had some help from my older brother and my teacher but mainly did it myself with some flow charts etc, so please forgive me if I haven't followed conventional rules and things of this nature, or if my code is messy. I will finalise it, just needed bait of help/support from the pro's.
This is my code and I have an issue with it. Once I have pressed 'y' and then 'y' again on the displayMenu() why doesn't it run oldUser()
Also, if any of you have any suggestion on what could make my code better, or I could improve it would be very helpful and I will take it on board.
import os # allows me to use functions defined elsewhere. os module allows for multi platforming.
import sys
words = []
users = {}
status = ""
def teacher_enter_words():
done = False
print 'Hello, please can you enter a word and definition pair.'
while not done:
word = raw_input('\nEnter a word: ')
deff = raw_input('Enter the definition: ')
# append a tuple to the list so it can't be edited.
words.append((word, deff))
add_word = raw_input('Add another word? (y/n): ')
if add_word.lower() == 'n':
done = True
def student_take_test():
student_score = 0
for pair in words:
print 'Definition:', pair[1]
inp = raw_input('Enter word: ')
student_score += check_error(pair[0], inp)
print 'Correct spelling:', pair[0], '\n'
print 'Your score:', student_score
def check_error(correct, inputt):
len_c = len(correct)
len_i = len(inputt)
# threshold is how many incorrect letters do we allow before a
# minor error becomes a major error.
# 1 - allow 1 incorrect letter for a minor error ( >= 2 becomes major error)
threshold = 1
# immediately check if the words are the same length
num_letters_incorrect = abs(len_c - len_i) # abs() method returns value of x - positive dist between x and zero
if num_letters_incorrect == 0:
for i in xrange(0, len(correct)):
if correct[i] != inputt[i]:
num_letters_incorrect += 1
if num_letters_incorrect <= threshold:
if num_letters_incorrect == 0:
return 2 # no incorrect letter.
else:
return 1 # minor error.
else:
return 0 # major error.
def displayMenu():
status = raw_input('Are you a registered user? y/n?: ')
if status == raw_input == 'y':
oldUser()
elif status == 'n':
newUser()
def newUser():
createLogin = raw_input('Create login name: ')
if createLogin in users:
print '\nLogin name already exist!\n'
else:
createPassw = raw_input('Create password: ')
users[createLogin] = createPassw
print '\nUser created!\n'
def oldUser():
login = raw_input('Enter login name: ')
passw = raw_input('Enter password: ')
if login in users and users[login] == passw:
print '\nLogin successful!\n'
else:
print "\nUser doesn't exist or wrong password!\n"
if __name__ == '__main__':
running = True
while running:
os.system('cls' if os.name == 'nt' else 'clear') # multi-platform, executing a shell command
reg = raw_input('Do you want to start the program? y/n?').lower()
if reg == 'y' or reg == 'yes':
displayMenu()
else: sys.exit(0)
inp = raw_input('Are you a Teacher or a Student? (t/s): ').lower()
if inp == 't' or inp == 'teacher':
teacher_enter_words()
else:
student_take_test()
running = False
raw_input is a function. status == raw_input == 'y' will never be true: that is comparing status with the function, and with 'y'.
I suspect that's simply a typo, and you just meant if status == 'y':