Spaces:
Sleeping
Sleeping
| 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}.") | |