Wesley Nazeazeno
Wesley Nazeazeno

Reputation: 135

Saving returned values to file

I'm pretty new on Python so I'm facing some problems. I was asked to create a code to read a file full of numbers. It has to select the most frequent 5 digits sequence in the file and save the output in a file. I was able to return the file and print it on the screen but could not store it a file. What am I doing wrong and why?

op = open('a.txt','r+').read()
rec = open("output.txt", "w")

def lseq(v,l): #value and length

    c = {} #dictionary
    for i in range(len(v)-l+1):
        key = v[i:i+l]
        c[key] = c.get(key,0)+1

    mx = max(c.values())
    return " ".join(item[0] for item in c.items() if item[1] == mx)

    print ("Done! The most frequent sequence is:")

print lseq(op, 5)

Upvotes: 0

Views: 570

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You need to file.write the list of maxes to you output file:

def lseq(f_in,f_out, l): #value and length
    # with will close your file automatically
    with open(f_in) as f, open(f_out, "w") as out:   
        c = {} #dictionary
        v = f.read()
        for i in range(len(v)-l+1):
            key = v[i:i+l]
            c[key] = c.get(key,0)+1
        mx = max(c.values())
        # create string of substrings equal to max count 
        # separated by a comma
        maxes = ",".join([item[0] for item in c.items() if item[1] == mx])
        # write formatted output to file
        out.write(maxes+"\n")
    # print the formatted output
    print("Done! The most frequent sequence is: {}".format(maxes))

You can also use a collections.Counter to do the counting for you:

def lseq(f_in,f_out, l): #value and length    
    with open(f_in) as f, open(f_out, "w") as out: 
         c = Counter(v[i:i+l] for i in range(len(v)-l+1)) #dictionary
         mx = c.most_common(1)[0][1]
         maxes = ",".join([sub for sub, count in c.items() if count == mx])
         out.write(maxes+"\n")
         print("Done! The most frequent sequence is: {}".format(maxes))

Upvotes: 1

Related Questions