0

I have a python project with function definitions written in CamelCase style. I'm trying to write a script to convert them to snake_case style.

CaseFormatter class

import re


class CaseFormatter:
   def __init__(self, file_directory):
       self.first_cap_re = re.compile('(.)([A-Z][a-z]+)')
       self.all_cap_re = re.compile('([a-z0-9])([A-Z])')
       self.functions_dict = {}
       self.file_directory = file_directory
       self.file = open(file_directory, "r", encoding="UTF-8")
       self.file_content = self.file.read()
       self.names_dictionary = {}

   def convert_camel_case_to_snake_case(self, name):
        """this function convert a camel case name to a snake case name """
       s1 = self.first_cap_re.sub(r'\1_\2', name)
       self.names_dictionary[name] = self.all_cap_re.sub(r'\1_\2', s1).lower()

   def find_camel_case_functions(self):
      """this function finds camel case functions in a file """
       s1 = re.findall("^\s*def (\S+)\s*\(\s*\S+\s*(?:,\s*\S+)*\):$", self.file_content)
    return s1

   def replace_functions(self):
       # file_content = open(self.file_directory, "r", encoding="UTF-8").read()
       self.file_content = self.file_content.replace(";", "")
       for key, val in self.names_dictionary.items():
           self.file_content = self.file_content.replace(key, val)
           # print(self.file_content)
       self.file = open(self.file_directory, "w", encoding="UTF-8")
       print(self.file_content)
       self.file.write(self.file_content)

testing the CaseFormatter class

import os
from CaseFormatter import *

walk_dir = 'some dirctory'

print('walk_dir = ' + walk_dir)
print('walk_dir (absolute) = ' + os.path.abspath(walk_dir))

for root, subDirs, files in os.walk(walk_dir):
    print('--\nroot = ' + root)

for filename in files:
    file_path = os.path.join(root, filename)
    if filename.endswith('.py') and filename != "__init__.py":
        print('\t- file %s (full path: %s)' % (filename, file_path))
        case_formatter = CaseFormatter(file_path)
        # print(case_formatter.find_camel_case_functions())
        for function_name in case_formatter.find_camel_case_functions():
            case_formatter.convert_camel_case_to_snake_case(function_name)
        print(case_formatter.names_dictionary)
        case_formatter.replace_functions()

I found the RegEx to find function definitions here. When I tried it on my project it gave me no results, the RegEx didn't work as I think. As an example of one of the files in the project:

class UnvoweledPattern(object):

   String = ''
   Rules = []
   IDs = []

   def __init__(self, string, rules, ids):

       self.String = string
       self.Rules = rules
       self.IDs = ids
       pass

   def GetRootsStringsAndRules(self, string):
       if (string == None):
           string = self.String

    rootStrings = []
       rootRules = []
       for j in range(len(self.Rules)):
           rootRule = ''
           rootString = ''
           for k in range(len(self.Rules[j])):
               rootRule += self.Rules[j][k]
               if self.Rules[j][k].isdigit():
                   rootString += string[int(self.Rules[j][k]) - 1]
               else:
                   rootString += self.Rules[j][k]
           rootStrings.append(rootString)
           rootRules.append(rootRule)

       return [rootStrings, rootRules]
Ali.Wassouf
  • 309
  • 4
  • 21
  • Don't use regex for this, but [parse your files to an AST](https://docs.python.org/3/library/ast.html) and extract methods from that. – Lucas Trzesniewski Sep 17 '17 at 10:35
  • Can you provide us an sample input? with camelCase function – Shakiba Moshiri Sep 17 '17 at 11:04
  • @k-five the function that converts from camel case to snake case is functioning correctly, the regex that searches for functions definitions is the problem. Also the last code snippet is an example – Ali.Wassouf Sep 17 '17 at 11:56
  • I know that the problem is with `regex`. I just wanted a real example to examine a pattern because I have no experience with python code – Shakiba Moshiri Sep 17 '17 at 12:19
  • if you have access **Perl** try this code: `perl -lpe '/def +[^ _(]+/g && s/((?=[A-Z]))(.)/"_".lc($2)/ge && s/(?<=def) +_/ /g' file` . If it worked then I would explain it to you how it works – Shakiba Moshiri Sep 17 '17 at 12:43

0 Answers0