Print text file as two separate lists - python-3.x

I am new to Python and stackoverflow :). I have a txt file which I need to print from. This is the txt file called DOB and has the following info:
Orville Wright 21 July 1988
Rogelio Holloway 13 September 1988
Marjorie Figueroa 9 October 1988
Debra Garner 7 February 1988
I need to print and display the list like this:
1. Orville Wright
2. Regelio Holloway
3. ......
list item
1. 21 July 1988
2. 13 September 1988
3. .......
My code below opens the txt file twice and I don't think that is effective. Help!
dob = open('DOB.txt', 'r')
for i, line in enumerate(dob, 1):
name = line.split()
name_surname = str(i) + "." + " " + name[0] + " " + name[1]
print(name_surname)
dob = open('DOB.txt', 'r')
for i, line in enumerate(dob, 1):
date = line.split()
day_to_year = str(i) + "." + " " + date[2] + " " + date[3] + " " + date[4]
print(day_to_year)
dob.close()

Calling read() reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read).
Once a file has been read, with read() you can use seek(0) to return the read cursor to the start of the file (docs are here). No need to open the file twice.
Use file.seek to jump to a specific position in a file. However, think about whether it is really necessary to go through the file again. Maybe there is a better option.
There can be another way of solving this problem, which is read the data once, have it saved in proper lists/variables and use it as you want. For example print it out in the format way you want.
#!/usr/bin/python
file = "/Users/rprakash/python/records.txt"
data = open(file, 'r')
for i, line in enumerate(data, 1):
details = line.split()
name = details[0] + " " + details[1]
print str(i) + ". " + name
data.seek(0)
for i, line in enumerate(data, 1):
details = line.split()
dob = details[2] + " " + details[3] + " " + details[4]
print str(i) + ". " + dob
Output:
1. Orville Wright
2. Rogelio Holloway
3. Marjorie Figueroa
4. Debra Garner
1. 21 July 1988
2. 13 September 1988
3. 9 October 1988
4. 7 February 1988

Related

Add suffix to a specific row in pandas dataframe

Im trying to add suffix to % Paid row in the dataframe, but im stuck with only adding suffix to the column names.
is there a way i can add suffix to a specific row values,
Any suggestions are highly appreciated.
d={
("Payments","Jan","NOS"):[],
("Payments","Feb","NOS"):[],
("Payments","Mar","NOS"):[],
}
d = pd.DataFrame(d)
d.loc["Total",("Payments","Jan","NOS")] = 9991
d.loc["Total",("Payments","Feb","NOS")] = 3638
d.loc["Total",("Payments","Mar","NOS")] = 5433
d.loc["Paid",("Payments","Jan","NOS")] = 139
d.loc["Paid",("Payments","Feb","NOS")] = 123
d.loc["Paid",("Payments","Mar","NOS")] = 20
d.loc["% Paid",("Payments","Jan","NOS")] = round((d.loc["Paid",("Payments","Jan","NOS")] / d.loc["Total",("Payments","Jan","NOS")])*100)
d.loc["% Paid",("Payments","Feb","NOS")] = round((d.loc["Paid",("Payments","Feb","NOS")] / d.loc["Total",("Payments","Feb","NOS")])*100)
d.loc["% Paid",("Payments","Mar","NOS")] = round((d.loc["Paid",("Payments","Mar","NOS")] / d.loc["Total",("Payments","Mar","NOS")])*100)
without suffix
I tried this way, it works but.. im looking for adding suffix for an entire row..
d.loc["% Paid",("Payments","Jan","NOS")] = str(round((d.loc["Paid",("Payments","Jan","NOS")] / d.loc["Total",("Payments","Jan","NOS")])*100)) + '%'
d.loc["% Paid",("Payments","Feb","NOS")] = str(round((d.loc["Paid",("Payments","Feb","NOS")] / d.loc["Total",("Payments","Feb","NOS")])*100)) + '%
d.loc["% Paid",("Payments","Mar","NOS")] = str(round((d.loc["Paid",("Payments","Mar","NOS")] / d.loc["Total",("Payments","Mar","NOS")])*100)) + '%'
with suffix
Select row separately by first index value, round and convert to integers, last to strings and add %:
d.loc["% Paid"] = d.loc["% Paid"].round().astype(int).astype(str).add(' %')
print (d)
Payments
Jan Feb Mar
NOS NOS NOS
Total 9991.0 3638.0 5433.0
Paid 139.0 123.0 20.0
% Paid 1 % 3 % 0 %

How to make my code work more efficiently

I made this grade calculator that calculates the grade form my school website. There are some minor flaws that do not affect the code, but does bug me. For example, When I paste the grade from the website, I have to press enter twice, which people who are using my program for the first time get confused with. Also, I want to make it so that the code does not create errors when I press enter without any data given in input.
Not only, these, but I want some feedback on my code and how I can improve them.
This is the code I worked on so far.
class color:
reset = '\\033\[0m'
class fg:
green = '\\033\[32m'
orange = '\\033\[33m'
\#getting input from user
def multi_input():
try:
while True:
data=input(color.fg.orange)
if not data: break
yield data
except KeyboardInterrupt:
return
restart=1
while restart!="x":
score = \[\]
percent = \[\]
add = \[\]
print(color.fg.green + "Enter Grade" + color.reset)
data = 0
data = list(multi_input())
#filter data into percent and score
for i in range(3, len(data),4):
data[i] = data[i].split('\t')
try:
percent.append(data[i][3])
score.append(data[i][4])
except IndexError:
result = 0
#take out ungraded values
percent = [value for value in percent if value != '']
score = [value for value in score if value != '']
#refine percent data
for i in range(len(percent)):
try:
percent[i] = percent[i].replace('%', '')
percent[i] = float(percent[i])
except ZeroDivisionError:
result = 0
#refine score data
for i in range(len(score)):
score[i] = score[i].split('/')
for j in range(len(score[i])):
score[i][j] = float(score[i][j])
try:
score[i] = score[i][0]/score[i][1]*100
except ZeroDivisionError:
result = 0
#amount of assignments
print()
print(color.fg.green + "graded assignments: ", len(score))
#calculation
for i in range(len(score)):
add.append(score[i]*percent[i]/100)
print(color.fg.green + "Percentage: ", f"{sum(add)/sum(percent)*100:05.2f}" + color.reset)
restart = input(color.fg.green + "press any key to start again, or x to exit.")
print()
This is a sample grade copied from my school website so that you can test my code out.
Nov
02
Projects & Labs
4.2 If statements & 4.3 Comparison A 1% 100/100 11/2/22
Nov
02
Quiz
4.2 If statements & 4.3 Comparison Quizzes A 0.4% 100/100 11/2/22
Oct
31
Projects & Labs
4.1 Booleans Labs A 1% 100/100 10/31/22
Oct
31
Quiz
4.1 Boolean Quiz A 0.4% 100/100 10/31/22
Oct
24
Exams & Tests
Python Console & Interaction Module Test A 12.5% 200/200 Test 18/20 Programming: 100(Extra 10 points Extra credit) 10/24/22
Oct
24
Homework
Study for Python Console & Interaction Quiz & Programming Test: Ungraded (Ungraded)
Oct
21
Projects & Labs
3.6 Comments Quiz & Lab C 1% 75/100 Quiz = 1/2 10/26/22
Oct
21
Projects & Labs
3.5 String Operators Labs A 2% 200/200 no screenshot of recipe 10/24/22

Need to print 10 different question booklets(aka Forms) but not able to print 9 of them as only the last one gets created and printed

import random
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois':
'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas':
'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine':
'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan':
'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri':
'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada':
'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton', 'NewMexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh',
'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence',
'South Carolina': 'Columbia'}
for quizNum in range(10):
quizFile = open('capitalsquiz%s.txt' % (quizNum + 1), 'w')
answerKeyFile = open('capitalsquiz_answers%s.txt' % (quizNum + 1), 'w')
quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
quizFile.write((' ' * 20) + 'State Capitals Quiz (Form %s)' % (quizNum + 1))
quizFile.write('\n\n')
states = list(capitals.keys())
random.shuffle(states)
for questionNum in range(40):
correctAnswer = capitals[states[questionNum]]
wrongAnswers = list(capitals.values())
del wrongAnswers[wrongAnswers.index(correctAnswer)]
wrongAnswers = random.sample(wrongAnswers, 3)
answerOptions = wrongAnswers + [correctAnswer]
random.shuffle(answerOptions)
quizFile.write('%s. What is the capital of %s?\n' % (questionNum + 1,states[questionNum]))
for i in range(4):
quizFile.write(' %s. %s\n' % ('ABCD'[i], answerOptions[i]))
quizFile.write('\n')
answerKeyFile.write('%s. %s\n' % (questionNum + 1, 'ABCD'[answerOptions.index(correctAnswer)]))
quizFile.close()
answerKeyFile.close()
The remaining 9 booklets are created as .txt files but are blank. Where am I going wrong ?
Questions involve the capital cities of U.S.A
Expected file form is :
Name:
Date:
Period:
State Capitals Quiz (Form 1)
What is the capital of West Virginia?
A. Hartford
B. Santa Fe
C. Harrisburg
D. Charleston
What is the capital of Colorado?
A. Raleigh
B. Harrisburg
C. Denver
D. Lincoln
3......
and so on . Like that for all the other files(remaining 9 .txt files which get created) questions would have to be printed.But they just turn out to be blank.
Each question booklets has the same questions but are in different order(to prevent cheating)
You questions loop is outside of the file loop. This is causing all of the files to be opened before any questions are written, then the last opened file is what gets the questions 👍
I can post the fix later if needed, just on my phone right now.

After a seperator there is a key in loop. How to keep it?

---------------------------
CompanyID: 000000000000
Pizza: 2 3.15 6.30
spaghetti: 1 7 7
ribye: 2 40 80
---------------------------
CompanyID: 000000000001
burger: 1 3.15 6.30
spaghetti: 1 7 7
ribye: 2 40 80
--------------------------
I'm doing a for loop over a list of lines. Every line is an item of a list. I need to keep the companyID while looking for a user input.
While this is printing the variable x=True. I cant take company ID to print it.
a='-'
for line in lines:
if a in line:
companyID= next(line)
if product in line:
x=True
TypeError: 'str' object is not an iterator
You can use your line seperator to identify when new data starts. Once you see the line with "----" then you can start collecing info in a new dictionary. for each line take its key and value by splitting on ":" and create the entry in the dictionary.
When you see the next "----" line you know thats the end of the data for this company so then do your check to see if they have the product and if so print the company id from the dictionary.
line_seperator_char = '-'
company_data = {}
product = 'burger'
with open('data.dat') as lines:
for line in lines:
line = line.rstrip()
if line.startswith(line_seperator_char):
if product in company_data:
print(f'{company_data["CompanyID"]} contains the product {product}')
company_data = {}
else:
key, value = line.split(':')
company_data[key] = value
OUTPUT
000000000001 contains the product burger
No it doesnt run. Could you explain what does "[1] means near split()[1]?
Another try that doesnt run is
y=[]
y=lines[1].split(' ')
for line in lines:
y=line.split(' ')
if len(y[1])==10:
companyID=y[1]
if product in line:
x=True
Thanks for the answers.Something that finally worked in my case was that:
y=[]
y=line[1].split(' ')
a='-'
for line in lines:
if line.startswith("CompanyID:"):
y=line.split(' ')
companyID=y[1]
if product in line:
x=True

How to convert excel data to json at frontend side

I want to convert some excel data to JSON. Plan is to get my excel file from D drive, read data and make some UI for this. Can any one please help me out?
Data is like this :-
country year 1 2 3 4
Netherlands 1970 3603 4330 5080 5820
Netherlands 1971 3436 4165 4929 5693
Netherlands 1972 3384 4122 4899 5683
Sweden 1970 1479 1963 2520 3132
Sweden 1971 1497 1985 2547 3163
Sweden 1972 1419 1894 2445 3055
You could of course always use Excel VBA, as you are already working with Excel. The following sub exports the used range of the current sheet as valid JSON into a .js-file:
Option Explicit
Sub jsonex()
Dim fname, q$, str$, lineend$, na, va, ur As Range, i%, j%, ncols%, nrows%
Set ur = Application.ActiveSheet.UsedRange
' set a few variables ...
na = ur.Rows(1): ncols = ur.Columns.Count: nrows = ur.Rows.Count: lineend = ",": q = """"
fname = "d:\tmp\data.js" ' prefedined filename
' fname = Application.GetSaveAsFilename ' or use file selector box ...
Open fname For Output As #1
Print #1, "var data=["
For i = 2 To ur.Rows.Count
va = ur.Rows(i)
str = ""
For j = 1 To ncols
str = str & "," & q & na(1, j) & q & ":" & q & va(1, j) & q
Next
If (i = nrows) Then lineend = "];"
Print #1, " {" & Mid(str, 2) & "}" & lineend
Next
Close #1
End Sub
This produces the file d:\tmp\data.js with
var data=[
{"Country":"Netherlands","year":"1970","1":"3603","2":"4330","3":"5080","4":"5820"},
{"Country":"Netherlands","year":"1971","1":"3436","2":"4165","3":"4929","4":"5693"},
{"Country":"Netherlands","year":"1972","1":"3384","2":"4122","3":"4899","4":"5683"},
{"Country":"Sweden","year":"1970","1":"1479","2":"1963","3":"2520","4":"3132"},
{"Country":"Sweden","year":"1971","1":"1497","2":"1985","3":"2547","4":"3163"},
{"Country":"Sweden","year":"1972","1":"1419","2":"1894","3":"2445","4":"3055"}];
Once you got it in this JSON format it is up to you to convert it into a different Array/Object structure by using plain JavaScript like
var da={};
data.slice(1).forEach(function(e){
var arr=[e[1],e[2],e[3],e[4]];
if (!da[e.country]) da[e.country]={}
da[e.country][e.year]=arr;
});
Maybe this is more the format you would like ("beautified" JSON.stringify(da)):
{"Netherlands":{"1970":["3603","4330","5080","5820"],
"1971":["3436","4165","4929","5693"],
"1972":["3384","4122","4899","5683"]},
"Sweden": {"1970":["1479","1963","2520","3132"],
"1971":["1497","1985","2547","3163"],
"1972":["1419","1894","2445","3055"]}}
Your JSON data could look like this:
[
{"country":"Netherlands', "year":1970, "1":3603, "2":4330, "3": 5080, "4":5820},
{"country":"Netherlands", "year":1971, ...}
...
]

Resources