Reputation: 129
I have a text file:
Jan Jansen heeft kaartnummer: 325255
Erik Materus heeft kaartnummer: 334343
Ali Ahson heeft kaartnummer: 235434
Eva Versteeg heeft kaartnummer: 645345
Jan de Wilde heeft kaartnummer: 534545
Henk de Vrie heeft kaartnummer: 345355
I need to print three things: the biggest int value, the number of lines and the line the biggest int is located in. I have done the first two, but I have no idea how to print the line the biggest int is located in. I hope you guys can help me.
This is what I got so far:
import re
num_lines = sum(1 for line in open("Kaartnummers.txt"))
print(num_lines)
int = open("Kaartnummers.txt", "r")
file = open("Kaartnummers.txt", "r")
file = file.read()
numbers = re.findall(r"[-+]?\d*\.\d+|\d+", file)
print(numbers)
numbers.sort()
print("The b"numbers[-1])
I know its very messy but I'm very new to coding and so I'm not very good.
Upvotes: 1
Views: 30
Reputation: 4551
Maybe this helps... A part of it uses python 3.6, but you can omit it it you have a file ready. The last few lines answer your immediate question.
import csv
from pathlib import Path
doc = """Jan Jansen heeft kaartnummer: 325255
Erik Materus heeft kaartnummer: 334343
Ali Ahson heeft kaartnummer: 235434
Eva Versteeg heeft kaartnummer: 645345
Jan de Wilde heeft kaartnummer: 534545
Henk de Vrie heeft kaartnummer: 345355"""
# recreating your file with data, python 3.6
# skip this line if you have the file already
Path("mydata.csv").write_text(doc)
with open("mydata.csv") as f:
reader = csv.reader(f)
rows = [row for row in reader]
# now you have your data inside interpreter as list of strings
print(rows)
# this seems to be common string in all the lines
sep = " heeft kaartnummer: "
# lets seperate name and values to be bale to play with them
rows2 = [row[0].split(sep) for row in rows]
print(rows2)
# lets associate the kaartnummer with a name in a dictionary
knum_dict = {int(num):name for name, num in rows2}
print(knum_dict)
#I need to print three things:
# the biggest int value,
# the number of lines
# and the line the biggest int is located in.
print()
print("Total number of lines:", len(rows))
max_num = max(knum_dict.keys())
print()
print("Biggest int:", max_num)
print("The biggest int is found for:", knum_dict[max_num])
#now back to your original quection -
#and the line the biggest int is located in
for i, row in enumerate(rows2):
if int(row[1]) == max_num:
#
print("The biggest int is found in line:", i+1)
print("(first line number is 1)"
Upvotes: 1