简体   繁体   English

传递值和从其他函数调用函数

[英]Passing values and calling functions from other functions

I have this class that consists of 3 functions. 我有包含3个功能的此类。 Each function is in charge of one part of the whole process. 每个功能负责整个过程的一部分。

.load() loads up two files, re-formats their content and writes them to two new files. .load()加载两个文件,重新格式化其内容并将其写入两个新文件。

.compare() takes two files and prints out their differences in a specific format. .compare()获取两个文件,并以特定格式打印出它们的差异。

.final() takes the result of .compare() and creates a file for every set of values. .final()获取.compare()的结果,并为.final()值创建一个文件。

Please ignore the Frankenstein nature of the logic as it is not my main concern at the moment. 请忽略逻辑的科学怪人性质,因为这不是我目前主要关注的问题。 I know it can be written a thousand times better and that's fine by me for now as i am still new to Python and programing in general. 我知道它的编写能力可以提高一千倍,这对我来说现在还好,因为我仍然不熟悉Python和常规编程。 I do have some theoretical experience but very limited technical practice and that is something i am working on. 我确实有一些理论经验,但是技术实践却非常有限,这是我正在努力的事情。

Here is the code: 这是代码:

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

Now to my question, how do i make it so each of the functions passes it's output files as values to the next function and calls it? 现在我的问题是,我该如何做,以便每个函数将其输出文件作为值传递给下一个函数并调用它?

So for an example: 举个例子:

running .load() should output two files, call the .compare() function passing it those two files. 运行.load()应该输出两个文件,调用.compare()函数传递这两个文件。

Then when .compare() is done, it should pass .final() the output file and calls it. 然后,当.compare()完成时,它应该将.final()输出文件传递并调用它。

So .final() will open whatever file is passed to it from .compare() and not "test123.txt" as it is defined above. 因此, .final()将打开从.compare()传递给它的任何文件,而不是上面定义的"test123.txt"

I hope this all makes sense. 我希望这一切都有意义。 Let me know if you need clarification. 让我知道您是否需要澄清。 Any criticism is welcome concerning the code itself. 欢迎对代码本身提出任何批评。 Thanks in advance. 提前致谢。

Do you mean call with the name of the two files? 你是说用两个文件的名字打电话吗? Well you defined a class, so you can just do: 好了,您定义了一个类,因此您可以执行以下操作:

def load(self, fileIn1, fileIn2, fileOut1, fileOut2):
    ... // do stuff here
    // when done
    self.compare( fileOut1, fileOut2 )

And so on. 等等。

There are a couple of ways to do this, but I would write a master function that calls the other three in sequence. 有两种方法可以做到这一点,但是我要编写一个主函数,依次调用其他三个函数。 Something like: 就像是:

def load_and_compare(self, input_file1, input_file2, output_file1, output_file2, result_file):
    self.load(input_file1, input_file2, output_file1, output_file2)
    self.compare(output_file1, output_file2)
    self.final(result_file)

Looking over your code, I think you have a problem in load. 查看代码,我认为您的加载有问题。 You only declare a single dictionary, then load the contents of both files into it and write those same contents out to two files. 您只声明一个字典,然后将两个文件的内容加载到其中,然后将相同的内容写到两个文件中。 Because each file has the same content, compare won't do anything meaningful. 因为每个文件具有相同的内容,所以比较不会做任何有意义的事情。

Also, do you really want to write out the file contents and then re-read it into memory? 另外,您是否真的要写出文件内容,然后将其重新读入内存? I would keep the frame definitions in memory for use in compare after loading rather than reading them back in. 我会将帧定义保留在内存中,以便在加载后进行比较,而不是读回它们。

I don't really see a reason for this to be a class at all rather than just a trio of functions, but maybe if you have to read multiple files with mildly varying formats you could get some benefit of using class attributes to define the format while inheriting the general logic. 我完全没有理由将它变成一个类,而不仅仅是三个函数,但是也许如果您必须读取格式略有不同的多个文件,则可以从使用类属性定义格式中受益同时继承一般逻辑。

I might be totally off here, but why don't you do it exactly as you're saying? 我可能会完全不在这里,但是为什么不按照您所说的去做呢?

Just call self.compare() out of your load() method. 只需从load()方法中调用self.compare()

You can also add return statements to load() and return a tuple with the files. 您还可以将return语句添加到load()并返回包含文件的tuple

Then add a 4th method to your class, which then collects the returned files and pipes them to the compare() method. 然后将第4个方法添加到您的类中,该方法将收集返回的文件并将其通过管道传递到compare()方法。

Best Regards! 最好的祝福!

One of the more powerful aspects of Python is that you can return something called a tuple . Python更强大的方面之一是您可以返回称为元组的东西。 To answer this in a more generic Python sense consider this code: 为了从更通用的Python角度回答这个问题,请考虑以下代码:

>>> def load(file1, file2):
        return file1+'.txt',file2+'.txt'

>>> def convert(file1, file2):
        return 'converted_'+file1,'converted_'+file2

>>> convert(*load("Java", "C#"))
('converted_Java.txt', 'converted_C#.txt')

Each function takes two named arguments, but the returned tuple of the first can be "unpacked" into the input arguments of the second by adding a * in front of it. 每个函数都有两个命名参数,但是可以通过在第一个返回的元组前面加一个*来“解包”到第二个输入参数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM