我有這個類由3個函數組成。每個功能都負責整個過程的一部分。從其他函數傳遞值和調用函數
加載兩個文件,重新格式化它們的內容並將它們寫入兩個新文件。
.compare()
需要兩個文件並以特定格式打印出它們的差異。
.final()
取.compare()
的結果,併爲每組值創建一個文件。
請忽略邏輯的科學怪人性質,因爲它目前不是我主要關心的問題。我知道它可以寫得好一千倍,現在我還是很好,因爲我仍然對Python和編程一般都不熟悉。我確實有一些理論經驗,但技術實踐非常有限,這正是我正在努力的方向。
下面是代碼:
from collections import defaultdict
from operator import itemgetter
from itertools import groupby
from collections import deque
import os
class avs_auto:
def load(self, fileIn1, fileIn2, fileOut1, fileOut2):
with open(fileIn1+'.txt') as fin1, open(fileIn2+'.txt') as fin2:
frame_rects = defaultdict(list)
for row in (map(str, line.split()) for line in fin1):
id, frame, rect = row[0], row[2], [row[3],row[4],row[5],row[6]]
frame_rects[frame].append(id)
frame_rects[frame].append(rect)
for row in (map(str, line.split()) for line in fin2):
id, frame, rect = row[0], row[2], [row[3],row[4],row[5],row[6]]
frame_rects[frame].append(id)
frame_rects[frame].append(rect)
with open(fileOut1+'.txt', 'w') as fout1, open(fileOut2+'.txt', 'w') as fout2:
for frame, rects in sorted(frame_rects.iteritems()):
fout1.write('{{{}:{}}}\n'.format(frame, rects))
fout2.write('{{{}:{}}}\n'.format(frame, rects))
def compare(self, f1, f2):
with open(f1+'.txt', 'r') as fin1:
with open(f2+'.txt', 'r') as fin2:
lines1 = fin1.readlines()
lines2 = fin2.readlines()
diff_lines = [l.strip() for l in lines1 if l not in lines2]
diffs = defaultdict(list)
with open(f1+'x'+f2+'Result.txt', 'w') as fout:
for line in diff_lines:
d = eval(line)
for k in d:
list_ids = d[k]
for i in range(0, len(d[k]), 2):
diffs[d[k][i]].append(k)
for id_ in diffs:
diffs[id_].sort()
for k, g in groupby(enumerate(diffs[id_]), lambda (i, x): i - x):
group = map(itemgetter(1), g)
fout.write('{0} {1} {2}\n'.format(id_, group[0], group[-1]))
def final(self):
with open('hw1load3xhw1load2Result.txt', 'r') as fin:
lines = (line.split() for line in fin)
for k, g in groupby(lines, itemgetter(0)):
fst = next(g)
lst = next(iter(deque(g, 1)), fst)
with open('final/{}.avs'.format(k), 'w') as fout:
fout.write('video0=ImageSource("MovieName\original\%06d.jpeg", {}, {}, 15)\n'.format(fst[1], lst[2]))
現在我的問題,我該如何使它所以每一個函數傳遞它的輸出文件作爲值到下一個功能,並調用它?
因此,對於一個例子:
運行應該輸出兩個文件,調用.compare()
函數傳遞這兩個文件。
然後當.compare()
完成後,它應該通過.final()
輸出文件並調用它。
因此,.final()
將打開從.compare()
傳遞給它的任何文件,而不是如上所定義的"test123.txt"
。
我希望這一切都有道理。讓我知道你是否需要澄清。對於代碼本身,任何批評都是值得歡迎的。提前致謝。
是的,你對我的負載的問題是正確的,我修好了,謝謝!我唯一的問題是,我如何通過open()行將「result_file」傳遞給final?如果我這樣做:「打開(result_file +'。txt','r')爲fin:」它返回「沒有這樣的文件或目錄」。你有可能把我指向正確的方向嗎? – MaxPower
那麼,那個錯誤意味着它沒有找到預期的文件 - 你需要確認它存在於你提供的位置。如果這意味着來自'compare'的輸出,那麼我可能會在master函數中構建我期望的文件名,並將它作爲參數傳遞給'compare'和'final',以確保它們。 –