Sajal
Sajal

Reputation: 4401

Read pattern from file and write to another file using python

i wish to read each function from the file, write it to a new file which is separate for each function.

input_file as:

function Script1(){
  var player = GetPlayer();
}    
function Script2(){
  var sVar1 = 3;    
}    
function Script3(){
  var sVar1 = 2;    
}

how do I copy the contents of each function?

Upvotes: 2

Views: 486

Answers (3)

Hugh Bothwell
Hugh Bothwell

Reputation: 56654

If the javascript source code is simple and nicely formatted to begin with, you might get by using regex.

For anything more involved, I would suggest a proper parser like pynarcissus.

Upvotes: 0

dwitvliet
dwitvliet

Reputation: 7671

You can use this regular expression, assuming all functions start on their own line (function SomeName()\n) and end on a new line (\n}), as in your example:

import re

with open('file.js', 'r') as f:
    content = f.read()

functions = re.findall(r'(function\s.+?\(.*?\)\n.+?\n\})', content, re.DOTALL)
for i, func in enumerate(functions):
    with open('func{}.js'.format(i), 'w') as f:
        f.write(func)

Remember re.DOTALL to make your regular expression match functions spanning over multiple lines.

Output example:

func1.js:

function Script1(){
  var player = GetPlayer();
}

Upvotes: 1

javidcf
javidcf

Reputation: 59711

You can just use regular expressions:

import re

with open('input_file.js', 'r') as file:
    script_str = file.read()

exp = re.compile(r'function\s+([^\s(]+)\s*\([^)]*\)\s*\{([^}]*)\}')
matches = exp.findall(script_str)
for m in matches:
    script_name, script_content = m[0], m[1].strip()
    with open('%s.js' % script_name, 'w') as file:
        file.write(script_content)

If you want to capture functions arguments too just add a group in the corresponding part of the regular expression (i.e. surround [^)]* with parentheses).

Upvotes: 0

Related Questions