2017-09-24 23 views
1

我有一个文本文件:打印从文本文件,从最大的int和给线这INT位于

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 

我需要打印三两件事:最大的int值,行数和最大的int所在的行。我已经完成了前两个,但我不知道如何打印最大的int所在的行。我希望你们能帮助我。

这是我走到这一步:

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]) 

我知道它很混乱,但我很新的编码,所以我不是很不错。

回答

1

也许这有助于...它的一部分使用Python 3.6,但你可以省略它,你有一个文件准备好了。最后几行回答你的直接问题。

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)"