سؤال

I have a python file with dozens of declarations of dozens of lists (this leads up to having several hundred such lists) like so: (pardon the placeholders)

def someFactoryMethod(self):
    self.myValues = [
    [<str literal>, <str literal>, <int literal>, <variable name>, <arbitrary literal>, <boolean literal>],
    # et cetera
    ]

I'm trying to refactor these lists into dictionaries instead, so I can use keys instead of standardized indices (which is not scaling anymore). How can I do this, short of manually editing the file? I've tried the following regex, with the hopes of using it to find such lines and then perform some sort of substitution:

self\.myVals\s*\=\s*\[\s*(\[\s*\'\w+\'\s*\,\s*\'\w+\'\s*\,\s*\d+\s*\,\s*\w+\s*\,r?[\'\"]{0,2}\w+]\'\"]{0,2}\s*\,\s*\w+\s*\,?\]\s*\,)+\s*\,?\]

But to no avail (I don't know if it's tripping up on newlines or what.)

For what it's worth, I was using that regex in Sublime Text 2.

هل كانت مفيدة؟

المحلول

Why not do it in python?

Import the file using python (which does the parsing), created the dict using your knowledge of the data structure), then use pprint.pprint to output a new python file?

==== Edit ====

An idea that might work is this, assuming the code actually runs. Add some code to each method that has these Lists of Lists (LoLs) that looks something like this

# Unique Marker #1 Start
self.myValues = [
    [<str literal>, <str literal>, <int literal>, <variable name>, <arbitrary literal>, <boolean  literal>],
]    
fixValues(self.myValues, "self.myValues", "Unique Marker 1")
# Unique Marker #1 End

Then fixValues looks like this:

def fixValues(lols, varname, markertext):
    lodicts = Whatever you need to do to convert the LoLs into a LoDs
    content = open(__file__, "rt").read()
    start = content.index(markertext) # Need to increment this to EOL
    end = content.index(markertext, start+len(markertext))  # Need to decrement this to BOL

    # Try it out on a temp file
    f = open(__file__, "wt")
    f.write(content[0:start])
    f.write("%s%s = ", " "*indent, varname)
    pprint.pprint(lodicts, f)
    f.write(content[end+len(markertext):]
    f.close()

You need to figure out the indent of for varname by counting spaces before it in the line it belongs on, some other things like that, and you probably want to write to a temp file while testing....

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top