从文件中调用方法并解析文件

时间:2015-10-18 02:21:01

标签: python class constructor

我做错了。它应该使用构造函数打开文件,并调用一个方法read_names_from_files(),它将解析上面计算每个单词的文件。作为空闲的一个例子,我运行了这个程序:

>>> import fish
>>> a = fish.Fishes("filename.txt")
>>> freqs = a.read_names_from_files()
>>> freqs
>>> {}

但它没有显示字典中的解析内容。

class Fishes:
def __init__(self, fn):
    self.file1 = open(fn, 'r')
    self.freqs=self.read_names_from_files()

def read_names_from_files(self):
    freqs = {}
    for line in self.file1:
        for word in line.split():
            if word in freqs:
                freqs[word] += 1
            else:
                freqs[word] = 1
    return freqs

1 个答案:

答案 0 :(得分:0)

这似乎有效。对不起,您的代码有太多错误让我讨论每个错误,甚至找出哪个是导致问题的主要原因。

class Fishes:
    def __init__(self, fn):
        self.file1 = open(fn, 'r')

    def read_names_from_files(self):
        freqs = {}
        for line in self.file1:
            for word in line.split():
                if word in freqs:
                    freqs[word] += 1
                else:
                    freqs[word] = 1
        return freqs

if __name__ == '__main__':
    import fish  # assume this file is named "fish.py"
    a = fish.Fishes("fish.py")  # read it as test data
    freqs = a.read_names_from_files()
    assert freqs['for'] == 2  # raise exception if untrue