如何在for循环的每次迭代中重置字典

How to reset dictionary on each iteration of for loop

下面是我的代码,用于打开目录中的每个文件并查找 class、函数、字符和行的数量。当我打印输出时,字典值相加,如何避免这种情况?

import os
class FileAnalyzer:
    
    def __init__(self, directory: str) -> None:
       
        self.directory: str = directory # NOT mandatory!
        self.files_summary: Dict[str, Dict[str, int]] = dict() 
        self.cnt=0
        self.c=0
        self.cc=0
        self.ct=0
        self.analyze_files() # summerize the python files data

    def analyze_files(self) -> None:
        
        
        for filename in os.listdir(self.directory):
            if filename.endswith(".py"):
                with open(os.path.join(self.directory, filename), 'r') as f:
                    
                    for line in f:
                        
                        self.c+=1
                        line = line.lstrip()    
                        if line.startswith("class "):
                            self.cnt+=1
                        
                        if line.startswith("def "):
                            self.ct+=1
                        # Move to the start of file
                        for i in line:
                            if not line.startswith(" "):
                                self.cc+=1
                        self.files_summary[filename] = {"class":self.cnt,"function":self.ct,"line":self.c,"char":self.cc}                    
                for k,v in self.files_summary.items():
                    print (k,v)

下面是我使用的两个输入文件:

file1.py:

definitely not function

This is def not a function def 

file2.py:

"""
    This file has:
        - 2 classes
        - 4 functions
        - 25 lines
        - 270 characters
"""

def func1():
    pass

def func2():
    pass

class Foo:
    def __init__(self):
        pass

class Bar:
    def __init__(self):
        pass


if __name__ == "__main__":
    main()

我得到的输出是:

file1.py {'class': 0, 'function': 0, 'line': 3, 'char': 56}
file1.py {'class': 0, 'function': 0, 'line': 3, 'char': 56}
file2.py {'class': 2, 'function': 4, 'line': 28, 'char': 275}

预期输出:

file1.py {'class': 0, 'function': 0, 'line': 3, 'char': 56}
file2.py {'class': 2, 'function': 4, 'line': 25, 'char': 219}

我得到了文件 1 的重复,并且在遍历第二个文件时也添加了计数。

    def analyze_files(self) -> None:
        for filename in os.listdir(self.directory):
            if filename.endswith(".py"):
                ...
                for k,v in self.files_summary.items():
                    print (k,v)

您正在每个循环中打印文件摘要。您可能希望在分析所有文件后打印文件摘要。

    def analyze_files(self) -> None:
        for filename in os.listdir(self.directory):
            if filename.endswith(".py"):
                ...
        for k,v in self.files_summary.items():
            print (k,v)

此外,您需要在每次循环后重置 self.cntself.ctself.cself.cc

        for filename in os.listdir(self.directory):

            if filename.endswith(".py"):
               ...
            self.cnt, self.ct, self.c, self.cc = 0, 0, 0, 0