Search user input from a string and print - python

I have a string called new_file that I read from a file with these contents:
;ASP718I
;AspA2I
;AspBHI 0 6 9 15 ...
;AspCNI
;AsuI 37 116 272 348
...
I am using name = raw_input ("enter the enzyme ")
to get data from the user and I am trying to print the corresponding fields from the above file (new_file).
For the input ;AspBHI I'd like the program to print the corresponding line from the file:
;AspBHI 0 6 9 15 ...
How can I achieve this?

This is a start:
db = dict((x.split(" ")[0], x) for x in new_file.split("\n"))
name = raw_input("enter the enzyme ")
print db[name]
Also try to be nice next time, people might help you with more enthusiasm and even explain their approach.

Related

How do I include the last instance of the condition met for the if statement?

I have a document that I am reading and writing to. Information is listed with a timestamp at the beginning of every entry. I am trying to populate the dateNTimeArr array with datetime objects for every entry but I notice that the last entry is not appending to the array, no matter how many entries I have. I'm not sure how to solve this.
this an example of the text file I am reading and writing to.
In this example, the array will populate with the datetime objects I create from the first and second entry but it doesn't append the last one.
2021-08-10 16:26:12
123
123
123
123
123
2021-08-10 16:26:28
123
123
123
123
123
2021-08-10 16:27:15
123
123
123
123
123
I tried removing the '\n' from the start of the while loop which seemed to work but the next time I ran the code, it messed with the format and kind of broke. Sorry in advance for the lack of structure to my code.
f = open("filename", "r")
dateNTimeArr = []
for line in f:
if "2021" in line:
datentime = line.split(" ")
datePart = datentime[0]
timePart = datentime[1]
hours, mins, secs = timePart.split(":")
year, month, day = datePart.split("-")
date1 = date(int(year), int(month), int(day))
time1 = time(int(hours), int(mins), int(secs))
datetime1 = datetime.combine(date1, time1)
dateNTimeArr.append(datetime1)
f.close()
f = open("filename", "a+")
submitBool = FALSE
while submitBool == FALSE:
f.write('\n')
f.write(now)
f.write('\n')
f.write(aQuantity.get())
f.write('\n')
f.write(bQuantity.get())
f.write('\n')
f.write(cQuantity.get())
f.write('\n')
f.write(dQuantity.get())
f.write('\n')
f.write(eQuantity.get())
submitBool = TRUE
f.close()
As Bramar mention, the list has 3 elements, you never printed it to check that.
Also, you have a few mistakes, in the while loop. The bool values are True and False not TRUE or FALSE.
And the loop will only run once because you changed it to True at the end of it.

Python 3.5 - Output from file

My goal is to have two programs. One will ask the user to input a test name and then a test score repeatedly until the user hits enter. This information will be stored in a .txt file. The second program will pull the information from the .txt file and print it into a format like something below with the test scores and a final average:
Reading six tests and scores
TEST SCORE
objects 88
loops 95
selections 86
variables 82
Average Test Score is
So far I have this for the first program to generate the txt document:
def main():
myfile = open('test.txt', 'w')
test = input('Please enter test name or enter to quit ')
while test != '':
score = int(input('Enter % score on this test '))
myfile.write(test + '\n')
myfile.write(str(score) + '\n')
test = input('Please enter test name or enter to quit ')
myfile.close()
print('File was created successfully')
main()
The second program looks like this and is in rough shape:
def main():
f = open('test.txt', 'r');
text = f.read();
f.close()
Main()
Any suggestions or examples? I’m really struggling.
First program / write
I recommend using \t between name and score instead of \n.
like this...
name1 100
name2 75
name3 10
...
It will help you when you read a file.
name, score = file.readline().split('\t')
Additionally, How about check input validation? whether input value in the valid range.
Second program / read
Using format is a nice way.
total, count = 0, 0
fmt = "{name:<16}\t{score:<5}"
header = fmt.format(name="TEST", score="SCORE")
print(header)
while ( ... ):
total += score
count += 1
... # read file
row = fmt.format(name=name, score=score)
print(row)
print("Average Test Score is ", total/count)

Sorting a file numerically

I am new to python and trying to create a maths quiz program towards the end of the program I want to be able to print all the results in the file ( stored in the variable Reverseinfo) in numerical order. This doesn't seem to work , regardless of if I use the .sort function or the sorted() function. Any help would be appreciated, thanks
ReverseInfo already has scores and names put into the file
ReverseInfo= (score + (" ") + Name)
ClassANum=open("Class A Results High to Low.txt","a")
ClassANum.write(ReverseInfo)
ClassANum.write(" \n")
ClassANum.close()
ClassBNum=open("Class B Results High to Low.txt","a")
ClassBNum.write(ReverseInfo)
ClassBNum.write(" \n")
ClassBNum.close()
ClassCNum=open("Class C Results High to Low.txt","a")
ClassCNum.write(ReverseInfo)
ClassCNum.write(" \n")
ClassCNum.close()
if Viewscores=="Y":
Classresults=input("Which Class would you like to see the results of?")
if Classresults=="A":
ClassA=open("Class A Results.txt","r")
Class=ClassA
alphabet=ClassA.readlines()
for line in sorted(alphabet):
print(line)
elif Classresults=="B":
ClassB=open("Class B Results.txt","r")
Class=ClassB
alphabet=ClassB.readlines()
for line in sorted(alphabet):
print(line)
elif Classresults=="C":
ClassC=open("Class C Results.txt","r")
Class=ClassC
alphabet=ClassC.readlines()
for line in sorted(alphabet):
print(line)
else:
print ("That is not valid")
Numerical=input(" Do you want to see the results alphabetically?")
if Numerical=="Y":
NumClassresults=input("Which Class would you like to see the results of?")
if NumClassresults=="A":
ClassA=open("Class A Results High to Low.txt","r")
Class=ClassA
Hightolow=ClassA.readlines()
for line in sorted(Hightolow):
print(line)
elif NumClassresults=="B":
ClassA=open("Class B Results High to Low.txt","r")
Class=ClassB
Hightolow=ClassB.readlines()
for line in sorted(Hightolow):
print(line)
if NumClassresults=="C":
ClassA=open("Class C Results High to Low.txt","r")
Class=ClassC
Hightolow=ClassC.readlines()
for line in sorted(Hightolow):
print(line)
the data stored in Class A is: 10 Jamie
8 Jamie
8 Peter
10 Ham
4 Jack
10 Joseph
9 jamie
9 Yuan
9 Bob
10 John
6 Nash
8 John
10 josh
10 Honey
there is currently nothing stored in Class b file
finally in class c:
9 jamie
9 Yuan
9 Bob
8 Peter
8 Jamie
4 Jack
10 Joseph
10 John
10 Jamie
10 Ham
Try below (assuming your file looks like Name 100 with many rows)
with open("Class C Results High to Low.txt","r") as f:
lines = [(int(line.split(" ")[0]), line.split(" ")[1]) for line in f.readlines()]
for l in sorted(lines, key=lambda score_name: score_name[0]):
print l
Please let me know if there are any syntax errors (leave a comment), I couldn't test this - on the phone at the moment.
If the file is just lines with one integer per line, Hightolow will be a list of strings (that can be passed to int)
You need to pass a key function to sorted (or sort). In this case int does exactly what you need.
sorted(Hightolow, key=int)
ie use it in the loop like this:
for line in sorted(Hightolow, key=int):
Alternatively you can make Hightolow a list of ints as you read the file
Hightolow = [int(x) for x in ClassA]

Formatting data in a text file using Python

I am fairly new to python and I am creating a program to try and take data from a text file, The quiz has 10 questions, and the name and scores of the users are saved in a text file. This is what the text file looks like:
Bob - 7
Steve - 4
Jake - 10
The idea is if the person tries again and gets another score, the program will realise the user already has data in the file, and it will be appended as such:
Bob - 7, 8, 3
The user can only save a maximum of 3 scores, e.g. If Bob tries again and gets a 10, the 7 will be removed and the 8 and 3 move one place forward like this:
Bob - 8, 3, 10
Then as an option, all the names and scores need to be read back in and placed in order of score with their names attached, If anyone could help that would be greatly appreciated.
Here is the code:
import random, time, re
name = input("Welcome, please type your name to continue: ")
class_number = input("What class are you in? (1, 2 or 3)")
class_number = ("H:\A453\\Class_"+class_number+".txt")
print("\nThank you", name, "you will now answer a short series of questions..\n")
score_counter = 0
x = 1
The Questions come here.... score_counter + 1 if correct etc..
f = open(class_number,"r")
contents = f.read()
items = re.findall(str(name+".*$"),contents,re.MULTILINE)
for y in items:
username, score = y.split(' - ')
print(username, score)
The part that adds the score to the database is here, but I have omitted it as I have yet to complete the bit above ^
f = open(class_number,"r")
f.write(str(name)+" - "+str(score_counter))
f.close()
Any help would be greatly appreciated, also I am not sure how to fix the problem of if for instance the user's name is Bob, and in the text file there is:
Bobby - 9
It will pull up Bobby's score instead, a fix for this would also be great.
Jake

Python Regex, Get Actual Line Back

I am trying to regex over an entire file, however I keep ending up with a list like this:
NONE
NONE
NONE
NONE
<_sre.SRE_Match object at 0x7f89b0152db0>
NONE
<_sre.SRE_Match object at 0x7f89b0152db0>
How do I get the actual line back?
Here is my code:
dictionaryFile = "file.txt"
patternMatch = re.compile('^(\w{6,8})(\s+)(\d+)(\s+)(.+)(\s+)(\d{1,3}\s*-\s*\d{1,3})')
with open(dictionaryFile) as file:
for line in file:
result = patternMatch.search(line)
print result
Here is an example of the file I am regex'ing over:
HETELAVL 2 IS THERE A TELEPHONE ELSEWHERE ON 35 - 36
WHICH PEOPLE IN THIS HOUSEHOLD CAN
BE CONTACTED?
EDITED UNIVERSE: HETELHHD = 2
VALID ENTRIES
1 YES
2 NO
HEPHONEO 2 IS A TELEPHONE INTERVIEW ACCEPTABLE? 37 - 38
EDITED UNIVERSE: HETELHHD = 1 OR HETELAVL = 1
VALID ENTRIES
1 YES
2 NO
I would like to get this back:
HETELAVL 2 IS THERE A TELEPHONE ELSEWHERE ON 35 - 36
HEPHONEO 2 IS A TELEPHONE INTERVIEW ACCEPTABLE? 37 - 38
search() returns None if no position in the string matches the pattern.
Check if the result is not None and print line:
result = patternMatch.search(line)
if result is not None:
print line
search returns a match object so don't just print it as it will print the object use result.group(0) to get the actual line.

Categories