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()
Related
I have a simple python script (meant to be run in terminal) that I want to compile, or at least make executable for PCs without python installed, so when I make an EXE with pyinstaller --onefile --nowindow random.py and send it over to my friend his windows defender stops it and even after getting around it at the list = open(fileName,'w+') it crashes. I have no idea why because it runs perfectly using python random.py
Here's the code:
import glob
import os
import random
a = True
while a == True:
x = input('Do you want to make a new savefile? (y/n): ')
if x == 'y':
fileName = input('\nWhat do you want its name to be? (put .txt at the end)\n')
list = open(fileName, 'w+')
addToList = True
a = False
elif x == 'n':
svfs = glob.glob("*.txt")
print('\nWhich save file do you want to use?\n', svfs)
fileName = input()
a = False
else:
print('Please give a valid answer (\"y\" for yes, \"n\" for no)')
if x == 'n':
print('\nDo you want to overwrite the selected savefile?')
if os.path.getsize(str(fileName)) == 0:
print('(The savefile is empty)')
else:
print('(The savefile isn\'t empty)')
b = input('(y/n): ')
if b == 'y':
list = open(fileName, 'w')
addToList = True
elif b == 'n':
addToList = False
else:
print('Please give a valid answer (\"y\" for yes, \"n\" for no)')
if addToList == True:
print("\nAdd items to the list:\n(type !done when you're done)")
while addToList == True:
string = input("\t")
if string == "!done":
addToList = False
else:
list.writelines([string, '; '])
list.close()
print(random.choice(open(str(fileName), 'r').readline().split('; ')))
input()
I am trying to make a contacts python project but I don't know how to fin da single user. I have tried to find from the file but I am not able to, kindly give the code for that part. If you find any other mistakes kindly resolve that too
This is the code.
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 19 17:56:45 2020
#author: Teerth Jain
"""
import time
from transpositionDecrypt import decryptMessage as dm
from transpositionEncrypt import encryptMessage as em
key = 8
users = {}
users1 = {}
print("Welcome to Teerth's Contacts Saver and Reader...")
time.sleep(0.5)
r_or_w = input("Do you want or (r)ead or (a)dd or (d)el contacts: ")
if r_or_w == 'r':
what = input("Do you want to read a single contact(y, n): ")
if what == 'y':
#here is the part where you need to give me advice#
if what == 'n':
print("Displaying the whole list...")
q = open('contacts.txt', 'r')
for liness in q:
print(dm(key, liness.strip()))
if r_or_w == 'a':
while True:
addwho = input("Please enter the name: ")
number = input("Please enter the number: ")
file2 = open('contacts.txt', 'r')
y = dm(key, file2.read())
if addwho in y:
print("User in contact list, please try again")
addwho = input("Please enter the name: ")
number = input("Please enter the number: ")
users1.update(addwho = number)
file1 = open('contacts.txt', 'a')
q = f'{addwho} : {number}'
file1.write(em(key, q))
file1.write("\n")
file1.close()
print("Number is ciphered and added.")
again = input("Do you want to add another contact(y, n): ")
if again == 'n':
break
There are no such errors now but if you can modify the code to make it better, kindly do it
Thanks
I am new to python and having some trouble outputting my data into a csv file. the script runs but the file is blank that is created with no data.
#!/usr/bin/env python3
import os
import smtplib
import csv
os.system('clear')
class CreateList(object):
def add_items(self):
shop_list = []
print("Lets create a shopping list for you..\n")
print("Please enter DONE when you have all the items needed for your shopping list.")
while True:
add_item = input("> ")
if add_item == 'DONE':
break
shop_list.append(add_item)
print("Here is your current shopping list:")
csv = open('shoplist.csv', 'w')
for item in shop_list:
print(item)
csv.write(item + '\n')
csv.close()
c = CreateList()
c.add_items()
You may just have some extra indentation. Here's the same script but some indentation has been removed on lines 19 and 20.
#!/usr/bin/env python3
import os
import smtplib
import csv
os.system('clear')
class CreateList(object):
def add_items(self):
shop_list = []
print("Lets create a shopping list for you..\n")
print("Please enter DONE when you have all the items needed for your shopping list.")
while True:
add_item = input("> ")
if add_item == 'DONE':
break
shop_list.append(add_item)
print("Here is your current shopping list:")
csv = open('shoplist.csv', 'w')
for item in shop_list:
print(item)
csv.write(item + '\n')
csv.close()
c = CreateList()
c.add_items()
There's an else missing. Your input is not appending anything to shop_list and thus nothing gets written to the file.
import os
import smtplib
import csv
os.system('clear')
class CreateList(object):
def add_items(self):
shop_list = []
print("Lets create a shopping list for you..\n")
print("Please enter DONE when you have all the items needed for your shopping list.")
while True:
add_item = input("> ")
if add_item == 'DONE':
break
else: # <<< missing
shop_list.append(add_item)
print("Here is your current shopping list:")
csv = open('shoplist.csv', 'w')
for item in shop_list:
print(item)
csv.write(item + '\n')
csv.close()
c = CreateList()
c.add_items()
import random
import pickle, shelve
import os
#import RPi.GPIO as GPIO | Raspberry pi only
import tkinter
import sys
import time
class Operator(object):
global list_name
def __init__(self):
print("Welcome to Python OS 1.0")
print("type 'help' to access help...") # ADD CODE OS.REMOVE("FILE")
def CheckDetails(self):
if not os.path.isfile( 'details.dat' ) :
data=[0]
data[0] = input('Enter Your Name: ' )
file= open( 'details.dat' , 'wb' )
pickle.dump( data , file )
file.close()
else :
File = open( 'details.dat' , 'rb' )
data = pickle.load( File )
file.close()
user = ""
while user != data[0]:
input("please enter your username...")
print( 'Welcome Back To Python OS, '+ data[0])
def Help(self):
print("""
write(sentence) - Prints the typed sentence on the screen
open(file, mode) - Opens the file and mode such as 'r'
create(listName) - creates the list, listName
add(data, listName) - adds the data to listName
remove(data, listName) - removes the selected data from listName
""")
def write(self, sentence):
print(sentence)
#classmethod
def create(self):
list_name = input("Please enter the list name...")
vars()[list_name] = []
time.sleep(1)
print("List (" + list_name + ") created")
def add(self):
data = input("Please specify the data to be added...")
list_name += data
def remove(self, data, list_name):
remove_data = input("Plese specify the data to be removed...")
list_name -= data
def main():
os = Operator()
os.CheckDetails()
ans = ""
ans = ans.lower()
while ans != "quit":
ans = input()
if ans == "write":
os.write()
elif ans == "help":
os.Help()
elif ans == "create":
os.create()
elif ans == "add":
os.add()
elif ans == "remove":
os.remove()
elif ans == "quit":
break
else:
print("Sorry, that command does not exist or it will be added into a future update...")
print("goodbye...")
main()
I am trying to make some sort of simplified python, but hitting errors only on the CheckDetails() function. I'm pickling data (which is fine) but getting errors when making the user check his or her username is correct, I've tested it and even though I have typed in the correct username, it carry's on asking for my username. Can anyone please help?
You have a while loop that will execute forever because you are not assigning your user variable to anything.
while user != data[0]:
user = input("please enter your username...")
print( 'Welcome Back To Python OS, '+ data[0])
I have written an application in Python to work with strings, i made a menu prompt from which i can select an operation to do, i tested all the functions, they work well, except the menu and main functions, that when i enter my choice nothing happens. Here's the code:
import re
import os
def searchInFile(searched, file):
try:
f = open(file)
except IOError.strerror as e:
print("Couldn't open the file: ", e)
else:
sea = re.compile(searched, re.IGNORECASE)
for line in f:
if re.search(sea, line):
print(line, end='')
def validateWithPattern(string):
patt = re.compile('([a-z0-9-_.])+#([a-z]+.)([a-z]{2,3})', re.IGNORECASE)
if re.search(patt, string):
print("Valid")
else:
print("Not valid!")
def menu():
print("|================MENU=================|\n", end='')
print("|0- Exit the program |\n", end='')
print("|1- Validate mail address |\n", end='')
print("|2- Search a string in a file |\n", end='')
print("|=====================================|\n", end='')
b = input("->")
return b
def main():
b = 10
while b != 0:
b = menu()
if b == 1:
a = input('Enter you mail address: ')
validateWithPattern(a)
elif b == 2:
a = input('Enter the file name: ')
c = input('Enter the string: ')
searchInFile(c, a)
elif b == 0:
os.system("PAUSE")
else: print("Choice error")
if __name__ == "__main__":
main()
Your b variable you are returning from menu function is a string, not an integer, so you can't compare it with numbers (input is automatically saved as string). If you use return int(b) instead of return b, it will be ok.
Also, I think your else: print("Choice error") should be indented the same way your if and elif are, since you probably want to write "Choice error" only if b is not one of given choices. The way it is indented in your code will print "Choice error" after the while loop ends and it will not print that message if you input the value it can't recognize (for example 3).