Skip to content

Instantly share code, notes, and snippets.

@bigsnarfdude bigsnarfdude/extractor.py
Last active Aug 9, 2019

Embed
What would you like to do?
extractor.py
from slimit.parser import Parser
from slimit.visitors import nodevisitor
from slimit import ast
import re
def check_code_sanity(sequence):
parser = Parser()
tree = parser.parse(sequence)
for node in nodevisitor.visit(tree):
if isinstance(node, ast.Identifier) and node.value == 'i':
node.value = 'hello'
return tree.to_ecma()
def get_input_file(text_file_name):
fh = open(text_file_name)
data = fh.readlines()
fh.close()
return data
def write_output_to_file(javascript_file_name, tree_name):
f = open(javascript_file_name,"a")
f.write(tree_name.to_ecma())
f.close()
def extract_comments(sequence):
pattern = "\/\/ .*\\n"
if re.match(pattern, sequence):
temp = re.match(pattern, sequence)
return temp.group().strip("\n")
else:
return ""
def extract_code(sequence):
pattern = "\/\/ .*\\n"
if re.match(pattern, sequence):
return re.split(pattern, sequence)[1]
else:
return ""
def strip_ending_characters(sequence):
try:
temp = data[i].split(splitter)[1].replace('\n', '', 1)
if re.findall("\)$", temp):
temp2 = temp[:-1]
return temp2
except:
return ""
def main():
text_file_name = 'node_text.txt'
javascript_file_name = 'node_text.js'
splitter = "get_ipython().run_cell_magic('node', '',"
data = get_input_file(text_file_name)
for i in range(len(data)):
sequence = data[i]
comments_js = extract_comments(sequence)
dirty_js = extract_code(sequence)
clean_js = check_code_sanity(dirty_js)
for code in [comments_js,clean_js]:
try:
temp_tree = check_code_sanity(code)
fh = write_output_to_file(javascript_file_name, temp_tree)
print(temp_tree.to_ecma())
except:
pass
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.