2

Problem

Given a file, for example:

#Example
x = 'foo = {}'

bar = {
  'color': 'blue'
}

print('Hello World')

Using regular expressions, the program will find variables names that are corresponding to dictionaries or set literals and print them. The output for the above would just be:

bar

A line like this

yes = { "no={}" }

Should only return yes.


The variables could be found with \w+? expression I'm just not sure where to start.

Current code

for line in open('program.txt'):
   array = line.split(' ')

   for item in array:
      if '{' in item:
         print(array[0])

This only functions properly for basic examples and there are some problems. Multiable variables on the same line don't work either. Also it doesn't use Regular Expressions.

2 Answers 2

1

You may do like this,

>>> s = '''#Example
x = 'foo = {}'

bar = {
  'color': 'blue'
}

print('Hello World')
yes = { "no={}" }'''
>>> re.findall(r'^\s*(\w+)\s*=\s*\{[^}]*\}', s, re.M)
['bar', 'yes']

or

>>> [i for i in re.findall(r'\{(?:\{[^{}]*\}|[^{}])*\}|^\s*(\w+)\s*=\s*(?=\{)', s, re.M) if i]
['bar', 'yes']
>>> 

If you want to define it as a function, you may use the below.

def check(s):
    return [i for i in re.findall(r'\{(?:\{[^{}]*\}|[^{}])*\}|^\s*(\w+)\s*=\s*(?=\{)', s, re.M) if i]
Sign up to request clarification or add additional context in comments.

1 Comment

How would I modify the pattern so that it can find dictionaries in one line functions. Example: def check(): b = {} would output b.
1

Don't use regular expressions for this.

Well, that's probably a bit too strong. Don't just use regular expressions for this.

Start by matching the code against this regex:

(\w+)\s*=\s*(.*)

Then, take the second capturing group, and pass it through ast.literal_eval().

To wit:

results = {}
for line in file:
    match = re.match(r'(\w+)\s*=\s*(.*)')
    if match:
        try:
            results[match.group(1)] = ast.literal_eval(match.group(2))
        except ValueError:
            continue  # It wasn't a valid literal

Note that ast.literal_eval() does not handle set and byte literals in 2.x. This is yet another reason to upgrade to Python 3.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.