How can i sort data from a txt? - python

I need to sort this data chronologically, hopefully, by date and them by time, but right now I just want to sort it by date... the information is on a TXT file:
2022/5/10 at 10 the client Mari has appointment with the Dra. Windrunner
2022/1/5 at 2 the client Ian has appointment with the Dr. Stark
2022/1/4 at 10 the client Amy has appointment with the Dra. Windrunner
2022/1/5 at 2 the client Josh has appointment with the Dr. Stark
2022/2/22 at 5 the client Mike has appointment with the Dr. Pool
2022/2/22 at 4 the client Pedro has appointment with the Dr. Stark
This is my code right now:
Docs = ("Dr. Stark", "Dra. Windrunner", "Dr. Pool")
x = 0
loop = False
DocsConverter = {
"0" : "Dr. Stark",
"1" : "Dra. Windrunner",
"2" : "Dr. Pool",
"dr. stark": "Dr. Stark",
"dra. windrunner" : "Dra. Windrunner",
"dr. pool" : "Dr. Pool",
"stark" : "Dr. Stark",
"windrunner" : "Dra. Windrunner",
"pool" : "Dr. Pool"
}
with open("appointment_hospital.txt", "a") as file_ap:
pass
def menu():
option = input("select a option 1. new appointment 2.show appointments 3. Exit: (1/2/3)\n")
if option == "1":
new_appointment()
elif option == "2":
print_appointments()
elif option == "3":
file_ap.close()
exit()
else:
print("Wrong option")
def new_appointment():
global x
name_client = input("Enter the name of the client:\n")
schedule_day = input("Enter the year, month and the day of the appointment:(Y/M/D)\n")
schedule_time= input("Enter at what hour is the appointment:\n")
while x != 3:
print(f"{Docs[x]}, id = {x}")
x += 1
x = 0
which_doc = input("Enter the name or the Id of the doctor: ")
appointment_info = f"{schedule_day} at {schedule_time} the client {name_client} has appointment with the " \
f"{DocsConverter.get(which_doc)}\n"
with open("appointment_hospital.txt", "a") as file:
file.write(appointment_info)
#this is where i tried to sort the information in the txt
def print_appointments():
with open("appointment_hospital.txt", "r") as file:
lines_appointments = []
for line in file:
temp = line.split()
for i in temp:
lines_appointments.append(i)
lines_appointments.sort()
with open("sort_appointments", "w") as sort_file:
for i in lines_appointments:
sort_file.writelines(i)
sort_file.writelines(" ")
sort_file.close()
with open("sort_appointments", "w") as sort_file:
read_appointments = sort_file.read()
print(read_appointments)
while not loop:
menu()
So in def print_appointments(): I tried to sort the data, and this was my last tried, None of the ones I have done have given me a moderately positive result.

You have some mistakes:
no file extension open("sort_appointments"
to sort by dates residual split the file by lines
when writing a list to a file, you need to open it for appending "a"
when reading a file, you must put the letter "r"
def print_appointments():
with open("appointment_hospital.txt", "r") as file:
lines_appointments = []
for line in file:
lines_appointments.append(line)
lines_appointments.sort()
with open("sort_appointments.txt", "a") as sort_file:
sort_file.writelines(lines_appointments)
with open("sort_appointments.txt", "r") as sort_file:
read_appointments = sort_file.read()
print(read_appointments)
print_appointments()

Related

How to convert text file into json file?

I am new to python and I want to convert a text file into json file.
Here's how it looks like:
#Q Three of these animals hibernate. Which one does not?
^ Sloth
A Mouse
B Sloth
C Frog
D Snake
#Q What is the literal translation of the Greek word Embioptera, which denotes an order of insects, also known as webspinners?
^ Lively wings
A Small wings
B None of these
C Yarn knitter
D Lively wings
#Q There is a separate species of scorpions which have two tails, with a venomous sting on each tail.
^ False
A True
B False
Contd
.
.
.
.
^ means Answer.
I want it in json format as shown below.
Example:
{
"questionBank": [
{
"question": "Grand Central Terminal, Park Avenue, New York is the worlds",
"a": "largest railway station",
"b": "Longest railway station",
"c": "highest railway station",
"d": "busiest railway station",
"answer": "largest railway station"
},
{
"question": "Eritrea, which became the 182nd member of the UN in 1993, is in the continent of",
"a": "Asia",
"b": "Africa",
"c": "Europe",
"d": "Oceania",
"answer": "Africa"
}, Contd.....
]
}
I came across a few similar posts and here's what I have tried:
dataset = "file.txt"
data = []
with open(dataset) as ds:
for line in ds:
line = line.strip().split(",")
print(line)
To which the output is:
['']
['#Q What part of their body do the insects from order Archaeognatha use to spring up into the air?']
['^ Tail']
['A Antennae']
['B Front legs']
['C Hind legs']
['D Tail']
['']
['#Q What is the literal translation of the Greek word Embioptera', ' which denotes an order of insects', ' also known as webspinners?']
['^ Lively wings']
['A Small wings']
['B None of these']
['C Yarn knitter']
['D Lively wings']
['']
Contd....
The sentences containing commas are separated by python lists. I tried to use .join but didn't get the results I was expecting.
Please let me know how to approach this.
dataset = "text.txt"
question_bank = []
with open(dataset) as ds:
for i, line in enumerate(ds):
line = line.strip("\n")
if len(line) == 0:
question_bank.append(question)
question = {}
elif line.startswith("#Q"):
question = {"question": line}
elif line.startswith("^"):
question['answer'] = line.split(" ")[1]
else:
key, val = line.split(" ", 1)
question[key] = val
question_bank.append(question)
print({"questionBank":question_bank})
#for storing json file to local directory
final_output = {"questionBank":question_bank}
with open("output.json", "w") as outfile:
outfile.write(json.dumps(final_output, indent=4))
Rather than handling the lines one at a time, I went with using a regex pattern approach.
This also more reliable as it will error out if the input data is in a bad format - rather than silently ignoring a grouping which is missing a field.
PATTERN = r"""[#]Q (?P<question>.+)\n\^ (?P<answer>.+)\nA (?P<option_a>.+)\nB (?P<option_b>.+)\n(?:C (?P<option_c>.+)\n)?(?:D (?P<option_d>.+))?"""
def parse_qa_group(qa_group):
"""
Extact question, answer and 2 to 4 options from input string and return as a dict.
"""
# "group" here is a set of question, answer and options.
matches = PATTERN.search(qa_group)
# "group" here is a regex group.
question = matches.group('question')
answer = matches.group('answer')
try:
c = matches.group('option_c')
except IndexError:
c = None
try:
d = matches.group('option_d')
except IndexError:
d = None
results = {
"question": question,
"answer": answer,
"a": matches.group('option_a'),
"b": matches.group('option_b')
}
if c:
results['c'] = c
if d:
results['d'] = d
return results
# Split into groups using the blank line.
qa_groups = question_answer_str.split('\n\n')
# Process each group, building up a list of all results.
all_results = [parse_qa_group(qa_group) for qa_group in qa_groups]
print(json.dumps(all_results, indent=4))
Further details in my gist. Read more on regex Grouping
I left out reading the text and writing a JSON file.

i am making a search but when printing why does the second input also come in

The code I am using is as follow:
elif (menu == 4):
cari = input("Masukan Data Mahasiswa Yang Akan Dicari : ")
for mhs in data_semua_mhs:
if (mhs["nim"]==cari):
print('Nim : ',mhs['nim'])
print('Nama : ',mhs['nama'])
print('Gender : ',mhs['gender'])
print('Ipk : ',mhs['ipk'])
elif (mhs["nim"]!=cari):
print("Data Tidak Tersedia")
enter image description here
So you want to print "Data Tidak Tersedia" (data not available) if no student record is found, but you current system is the following: go through every student in the list. If it matches the id, print the data. If it does not match, print that the data is not available. However, this will print this for every student that does not match.
The following will print it only if no students match:
elif (menu == 4):
cari = input("Masukan Data Mahasiswa Yang Akan Dicari : ")
ada = False
for mhs in data_semua_mhs:
if (mhs["nim"]==cari):
ada = True
print('Nim : ',mhs['nim'])
print('Nama : ',mhs['nama'])
print('Gender : ',mhs['gender'])
print('Ipk : ',mhs['ipk'])
if ada is False:
print("Data Tidak Tersedia")

for loop prints "student not found" more than 1 time

I have a student management program and I use a for loop to look up in dictionaries inside a list so I have if and elif conditions to search for student data. However, it gives output with 3 or 4 elif conditions also. I want that if the program doesn't find student data it only prints "student not found" once and if I have student data only the if clause should run not elif.
import json
while True:
student={}
with open('Data file for student management system.json','r') as f:
students=json.load(f)
print('''\n"1 or add" to Add Student''')
print('''"2 or edit" to Edit Student''')
print('''"3 or delete" to Delete Student''')
print('''"4 or search" to Search Student''')
print('''"5 or display" to Display all Students''')
while True:
try:
option=str(input('''\nPlease enter any option given above:'''))
if option not in ['1','2','3','4','5','add','delete','edit','search','display']:
print('''\n"Please select a correct options"''')
else:
break
except ValueError:
print('''"Please enter a correct number only"''')
if option in ['1','add']:
student["Name"] = input ("\nStudent's Name:").title()
student["Father Name"] = input ("Father's Name:").title()
student["Age"] = input ("Student's Age:")
student["Address"] = input ("Address:").title()
students.append(student)
with open('Data file for student management system.json','w') as f:
json.dump(students,f)
student={}
print('''\n"Addition Successful"''')
elif option in ['2','edit']:
Name=input("\nPlease type name:").title()
new_name=input("\nWhat is new name:").title()
for s in list(students):
for d in s:
if s['Name']==Name:
s['Name']=new_name
print('''\n"Edit Successful"''')
with open('Data file for student management system.json','w') as f:
json.dump(students,f)
elif s['Name']!=Name:
print('''\n"Student not found"''')
break
elif option in ['3','delete']:
del_name=input("\nPlease type name of student you want to delete:").title()
for s in list(students):
for d in s:
if s['Name']==del_name:
ind=students.index(s)
while True:
sure=input('\nAre you sure you want to delete?\n\nYes or No:').lower()
if sure in ['yes','y']:
del students[ind]
print('''\n"Deletion Successful"''')
with open('Data file for student management system.json','w') as f:
json.dump(students,f)
break
elif sure in ['no','n']:
print("\nStudent data not deleted")
break
else:
print('''"\nPlease enter a coorect option"''')
break
elif s['Name']!=del_name:
print('''\n"Student not found"''')
break
elif option in ['4','search']:
s_name=input("\nEnter name of student:").title()
for d in students:
for k,v in d.items():
if d['Name']==s_name:
print(" ____________________________________________________________________________________________________________________________")
print("| | | | |")
print("| S-No | Name | Father Name | Address |")
print("|__________|________________________________|_________________________________|______________________________________________|")
print(f"| |{d['Name']: <32}|{d['Father Name']: <33}|{d['Address']: <46}|")
print("|__________|________________________________|_________________________________|______________________________________________|")
break
elif d['Name']!=s_name:
print('''\n"Student not found"''')
break
elif option in ['5','display']:
print(" ____________________________________________________________________________________________________________________________")
print("| | | | |")
print("| S-No | Name | Father Name | Address |")
print("|__________|________________________________|_________________________________|______________________________________________|")
for s in students:
for k,v in s.items():
pass
print(f"| |{s['Name']: <32}|{s['Father Name']: <33}|{s['Address']: <46}|")
print("|__________|________________________________|_________________________________|______________________________________________|")
while True:
Repeat=input("\nDo you want to repeat?\n\nYes or No:")
Repeat=Repeat.lower()
if Repeat not in ["yes","y","no","n"]:
print("\nPlease select correct option")
else:
break
if Repeat in ["yes","y"]:
continue
else:
if Repeat in ["no","n"]:
print("\n-----Thank you for using-----")
input()
break
json file
[{"GR#": 1, "Name": "Daniyals", "Age": 12, "Father Name": "Ajaz", "Address": "Flat-123, Block ABC"}, {"GR#": 2, "Name": "Shahrukh Khan", "Age": 9, "Father Name": "Ajeeb Khan", "Address": "Khan Mansion"}, {"Name": "Waseem Munir", "Father Name": "Sdasd", "Age": "asdasdas", "Address": "Asdasdas"}, {"Name": "Saad", "Father Name": "Asdsadas", "Age": "asdasdas", "Address": "Asdas"}, {"Name": "Sdasd", "Father Name": "Adsadas", "Age": "dasdas", "Address": "Dasdas"}]
I suggest use pandas dataFrame it will make it so much easier.
import pandas as pd
df = pd.DataFrame(
{'Name': ['a','b','c','d'], #Your name list here
'Fathers Name': np.zeros(4), #Your data here
'Address': np.zeros(4), #Your data here and add more columns
})
s_name=input("\nEnter name of student:").title()
for i in range(len(df)):
if df['Name'][i] == s_name:
print(df.loc[i])

How to print list of lists without extra brackets and quotes?

I'm working on assignment for my Python 3 programming class. It's a database to look up movies and the year they came out. However, I'm having a hard time printing the output without extra brackets and quotes:
# Build a dictionary containing the specified movie collection
list_2005 = [["Munich", "Steven Spielberg"]]
list_2006 = [["The Departed", "Martin Scorsese"], ["The Prestige", "Christopher Nolan"]]
list_2007 = [["Into the Wild", "Sean Penn"]]
movies = {
'2005': list_2005,
'2006': list_2006,
'2007': list_2007
}
# Prompt the user for a year
# Displaying the title(s) and directors(s) from that year
user_year = str(input("Enter a year between 2005 and 2007:\n"))
if user_year in movies:
for name in movies[user_year]:
print("%s" % ', '.join(name))
print()
elif user_year not in movies:
print("N/A")
# Display menu
user_choice = ''
while user_choice != 'q':
print("MENU\nSort by:\ny - Year\nd - Director\nt - Movie title\nq - Quit")
print()
user_choice = str(input("Choose an option:\n"))
if user_choice == 'y':
for key, value in sorted(movies.items()):
print("%s:" % key)
print(" %s" % ''.join(str(movies[key])))
# Carry out the desired option: Display movies by year,
# display movies by director, display movies by movie title, or quit
I would like this output to be:
2005:
Munich, Steven Spielberg
2006:
The Prestige, Christopher Nolan
The Departed, Martin Scorsese
etc.
The output I am getting:
2005:
['Munich', 'Steven Spielberg']
2006:
[['The Prestige', 'Christopher Nolan'], ['The Departed', 'Martin Scorsese']]
etc.
Replace
print(" %s" % ''.join(str(movies[key])))
with
print("\t" + '\n\t'.join("{}, {}".format(m[0], m[1]) for m in movies[key]))

Error when creating dictionaries from text files

I've been working on a function which will update two dictionaries (similar authors, and awards they've won) from an open text file. The text file looks something like this:
Brabudy, Ray
Hugo Award
Nebula Award
Saturn Award
Ellison, Harlan
Heinlein, Robert
Asimov, Isaac
Clarke, Arthur
Ellison, Harlan
Nebula Award
Hugo Award
Locus Award
Stephenson, Neil
Vonnegut, Kurt
Morgan, Richard
Adams, Douglas
And so on. The first name is an authors name (last name first, first name last), followed by awards they may have won, and then authors who are similar to them. This is what I've got so far:
def load_author_dicts(text_file, similar_authors, awards_authors):
name_of_author = True
awards = False
similar = False
for line in text_file:
if name_of_author:
author = line.split(', ')
nameA = author[1].strip() + ' ' + author[0].strip()
name_of_author = False
awards = True
continue
if awards:
if ',' in line:
awards = False
similar = True
else:
if nameA in awards_authors:
listawards = awards_authors[nameA]
listawards.append(line.strip())
else:
listawards = []
listawards.append(line.strip()
awards_authors[nameA] = listawards
if similar:
if line == '\n':
similar = False
name_of_author = True
else:
sim_author = line.split(', ')
nameS = sim_author[1].strip() + ' ' + sim_author[0].strip()
if nameA in similar_authors:
similar_list = similar_authors[nameA]
similar_list.append(nameS)
else:
similar_list = []
similar_list.append(nameS)
similar_authors[nameA] = similar_list
continue
This works great! However, if the text file contains an entry with just a name (i.e. no awards, and no similar authors), it screws the whole thing up, generating an IndexError: list index out of range at this part Zname = sim_author[1].strip()+" "+sim_author[0].strip() )
How can I fix this? Maybe with a 'try, except function' in that area?
Also, I wouldn't mind getting rid of those continue functions, I wasn't sure how else to keep it going. I'm still pretty new to this, so any help would be much appreciated! I keep trying stuff and it changes another section I didn't want changed, so I figured I'd ask the experts.
How about doing it this way, just to get the data in, then manipulate the dictionary any ways you want.
test.txt contains your data
Brabudy, Ray
Hugo Award
Nebula Award
Saturn Award
Ellison, Harlan
Heinlein, Robert
Asimov, Isaac
Clarke, Arthur
Ellison, Harlan
Nebula Award
Hugo Award
Locus Award
Stephenson, Neil
Vonnegut, Kurt
Morgan, Richard
Adams, Douglas
And my code to parse it.
award_parse.py
data = {}
name = ""
awards = []
f = open("test.txt")
for l in f:
# make sure the line is not blank don't process blank lines
if not l.strip() == "":
# if this is a name and we're not already working on an author then set the author
# otherwise treat this as a new author and set the existing author to a key in the dictionary
if "," in l and len(name) == 0:
name = l.strip()
elif "," in l and len(name) > 0:
# check to see if recipient is already in list, add to end of existing list if he/she already
# exists.
if not name.strip() in data:
data[name] = awards
else:
data[name].extend(awards)
name = l.strip()
awards = []
# process any lines that are not blank, and do not have a ,
else:
awards.append(l.strip())
f.close()
for k, v in data.items():
print("%s got the following awards: %s" % (k,v))

Categories