2016-05-05 2 views
2

Problem ist es, den Namen des Ereignisses zurückzugeben, die die höchste Teilnehmerzahl in dieser Textdatei hat:Python Datei-IO - Aufbau Wörterbuch und und die Suche nach Maximalwert

#Beyond the Imposter Syndrome 
32 students 
4 faculty 
10 industries 
#Diversifying Computing Panel 
15 students 
20 faculty 
#Movie Night 
52 students 

Also dachte ich, dass ich es zu teilen hatte in ein Wörterbuch mit den Schlüsseln als Ereignisnamen und den Werten als Summe der Ganzzahlen am Anfang der anderen Zeilen. Ich habe viel Ärger und ich denke ich mache es zu kompliziert als es ist.

Dies ist, was ich bisher:

def most_attended(fname): 
    '''(str: filename,)''' 
    d = {} 
    f = open(fname) 
    lines = f.read().split(' \n') 
    print lines 
    indexes = [] 
    count = 0 
    for i in range(len(lines)): 
     if lines[i].startswith('#'): 
      event = lines[i].strip('#').strip() 
      if event not in d: 
       d[event] = [] 
      print d 
      indexes.append(i) 
      print indexes 
     if not lines[i].startswith('#') and indexes !=0: 
      num = lines[i].strip().split()[0] 
      print num 
      if num not in d[len(d)-1]: 
       d[len(d)-1] += [num] 
    print d 

    f.close() 

Antwort

1

Hier ist, wie ich es tun würde.

with open("test.txt", "r") as f: 
    docText = f.read() 

eventsList = [] 

#start at one because we don't want what's before the first # 
for item in docText.split("#")[1:]: 
    individualLines = item.split("\n") 
    #get the sum by finding everything after the name, name is the first line here 
    sumPeople = 0 
    #we don't want the title 
    for line in individualLines[1:]: 
     if not line == "": 
      sumPeople += int(line.split(" ")[0]) #add everything before the first space to the sum 
    #add to the list a tuple with (eventname, numpeopleatevent) 
    eventsList.append((individualLines[0], sumPeople)) 

#get the item in the list with the max number of people 
print(max(eventsList, key=lambda x: x[1])) 

Im Wesentlichen wollen Sie zuerst das Dokument von # aufzuspalten, das erste Element zu ignorieren, weil das immer leer sein wird. Jetzt haben Sie eine Liste von Ereignissen. Jetzt müssen Sie für jedes Ereignis durchgehen, und für jede zusätzliche Zeile in diesem Ereignis (außer dem ersten) müssen Sie diesen Zeilenwert zur Summe hinzufügen. Dann erstellen Sie eine Liste von Tupeln wie (eventname) (numPeopleAtEvent). Schließlich verwenden Sie max(), um den Artikel mit der maximalen Anzahl von Personen zu erhalten.

Dieser Code druckt ('Movie Night', 104) offensichtlich Sie sie formatieren können, wie Sie wollen

+0

DANKE! Genau das habe ich versucht! Ich war mit der ganzen Trennung verwirrt. Ich habe die Max-Notation noch nicht gelernt, also habe ich nur eine kleine Schleife geschrieben, um das Maximum in der Liste der Tupel zu finden. – holophrasm

2
import sys 
from collections import defaultdict 
from operator import itemgetter 

def load_data(file_name): 
    events = defaultdict(int) 
    current_event = None 
    for line in open(file_name): 
     if line.startswith('#'): 
      current_event = line[1:].strip() 
     else: 
      participants_count = int(line.split()[0]) 
      events[current_event] += participants_count 
    return events 


if __name__ == '__main__': 
    if len(sys.argv) < 2: 
     print('Usage:\n\t{} <file>\n'.format(sys.argv[0])) 
    else: 
     events = load_data(sys.argv[1]) 
     print('{}: {}'.format(*max(events.items(), key=itemgetter(1)))) 
0

ähnliche Antworten auf den oben genannten hat.

result = {}   # store the results 
current_key = None # placeholder to hold the current_key 

for line in lines: 
    # find what event we are currently stripping data for 
    # if this line doesnt start with '#', we can assume that its going to be info for the last seen event 
    if line.startswith("#"): 
     current_key = line[1:] 
     result[current_key] = 0 
    elif current_key: 
     # pull the number out of the string 
     number = [int(s) for s in line.split() if s.isdigit()] 
     # make sure we actually got a number in the line 
     if len(number) > 0: 
      result[current_key] = result[current_key] + number[0] 

print(max(result, key=lambda x: x[1])) 

Dies wird "Movie Night" drucken.

0

Sie können es ohne Wörterbuch tun und es vielleicht ein wenig einfacher machen, wenn nur Listen mit:

with open('myfile.txt', 'r') as f: 
    lines = f.readlines() 
    lines = [l.strip() for l in lines if l[0] != '#'] # remove comment lines and '\n' 
    highest = 0 
    event = "" 
    for l in lines: 
     l = l.split() 
     if int(l[0]) > highest: 
      highest = int(l[0]) 
      event = l[1] 

print (event) 
0

Ihre Problembeschreibung besagt, dass Sie das Ereignis mit der höchsten Teilnehmerzahl finden möchten. Ich habe eine Lösung versucht, die keine Liste oder kein Wörterbuch verwendet.

Ps: Ich bin neu in Python.

bigEventName = "" 
participants = 0 

curEventName = "" 
curEventParticipants = 0 

# Use RegEx to split the file by lines 
itr = re.finditer("^([#\w+].*)$", lines, flags = re.MULTILINE) 

for m in itr: 
    if m.group(1).startswith("#"): 
     # Whenever a new group is encountered, check if the previous sum of 
     # participants is more than the recent event. If so, save the results. 
     if curEventParticipants > participants: 
      participants = curEventParticipants 
      bigEventName = curEventName 

     # Reset the current event name and sum as 0 
     curEventName = m.group(1)[1:] 
     curEventParticipants = 0 
    elif re.match("(\d+) .*", m.group(1)): 
     # If it is line which starts with number, extract the number and sum it 
     curEventParticipants += int(re.search("(\d+) .*", m.group(1)).group(1)) 

# This nasty code is needed to take care of the last event 
bigEventName = curEventName if curEventParticipants > participants else bigEventName 

# Here is the answer 
print("Event: ", bigEventName) 
Verwandte Themen