File size: 1,311 Bytes
e282277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import ast

def get_dict_variable_names(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        node = ast.parse(file.read(), filename=file_path)

    dict_variable_names = []

    class DictVariableVisitor(ast.NodeVisitor):
        def visit_Assign(self, node):
            for target in node.targets:
                if isinstance(target, ast.Name):
                    # Check if the assigned value is a dictionary
                    if isinstance(node.value, ast.Dict):
                        dict_variable_names.append(target.id)
            self.generic_visit(node)

    DictVariableVisitor().visit(node)

    return dict_variable_names

def write_variables_to_file(variables, output_file):
    with open(output_file, 'w', encoding='utf-8') as file:
        file.write("variables = [\n")
        for var in variables:
            file.write(f"    '{var}',\n")
        file.write("]\n")

# Example usage
input_file_path = 'paragraphs2.py'  # Replace with your input file path
output_file_path = 'variables.py'  # Replace with your desired output file path

dict_variables = get_dict_variable_names(input_file_path)
write_variables_to_file(dict_variables, output_file_path)

print(f"Initialized dictionary variables stored in {output_file_path}.")