将返回值保存到文件

时间:2015-08-23 17:14:55

标签: python python-2.7

我对Python很新,所以我遇到了一些问题。 我被要求创建一个代码来读取一个充满数字的文件。它必须在文件中选择最常见的5位数序列并将输出保存在文件中。 我能够返回文件并将其打印在屏幕上,但无法将其存储为文件。我做错了什么,为什么?

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)

1 个答案:

答案 0 :(得分:1)

您需要file.write输出文件的最大值列表:

((View)elem.getParent().getParent()).getId()==R.id.parent_id

你也可以使用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)) 为你做计数:

collections.Counter