0

Below you can see the function for extracting separate words from the text. Below you can see the text and code.

import re

text = '''

def function_cal(revenues_shops, surplus_margin, meadian_profit):
     median_profit= revenues_shops* surplus_margin
     return median_profit
 
def function_cal_new (revenues_stories_new, surplus_margin_new, meadian_profit):
     median_profit= revenues_stories_new* surplus_margin_new
     return median_profit   
 
def function_cal_new1 (revenues_stories_new1, surplus_margin_new1, meadian_profit):
     median_profit= revenues_stories_new1* surplus_margin_new1
     return median_profit      
    
'''
    
def extraction_variables(text):
    splited_table1, splited_table2 = dict(), dict()
    lines = text.split('\n')
    for line in lines:
            x = re.search(r"^def.*:$", line)
            if x is not None:
                values = x[0].split('def ')[1].split('(')
                splited_table1 = values[0]
                splited_table2 = values[1][:-2].split(', ')
                return splited_table1, splited_table2

splited_table1, splited_table2 = extraction_variables(text)
splited_table1  
splited_table2  

This function extracts only one value from the first part of the text while other parts are not extracted. So can anybody help me how to solve this problem and store all words from text above in splited_table1 and splited_table2? For example splited_table1 need to contain function_cal, function_cal_new and function_cal_new1.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
silent_hunter
  • 2,224
  • 1
  • 12
  • 30
  • Does this answer your question? [How can I use \`return\` to get back multiple values from a loop? Can I put them in a list?](https://stackoverflow.com/questions/44564414/how-can-i-use-return-to-get-back-multiple-values-from-a-loop-can-i-put-them-i) – mkrieger1 Oct 10 '22 at 13:18
  • 1
    consider using the `ast` module for parsing python source code. – gog Oct 10 '22 at 13:18
  • @mkrieger1 This example maybe is good but not work for me. Please if you can share concrete answer – silent_hunter Oct 10 '22 at 13:28
  • @silent_hunter Can you also print your expected output what you want at the end in splitted_table_1 and splitted_table_2 – Deepak Tripathi Oct 10 '22 at 13:30
  • @ Deepak Tripathi Expected output is also printed you can see this in the last sentence of the post for splited_table1. For the splited_table2 output is (revenues_shops, surplus_margin, meadian_profit,revenues_stories_new, surplus_margin_new, meadian_profit,revenues_stories_new1, surplus_margin_new1, meadian_profit) – silent_hunter Oct 10 '22 at 13:34

2 Answers2

1

You can try with creating temporary python file out of your text and then extracting function object from that file dynamically like this

text = '''

def function_cal(revenues_shops, surplus_margin, meadian_profit):
     median_profit= revenues_shops* surplus_margin
     return median_profit
 
def function_cal_new (revenues_stories_new, surplus_margin_new, meadian_profit):
     median_profit= revenues_stories_new* surplus_margin_new
     return median_profit   
 
def function_cal_new1 (revenues_stories_new1, surplus_margin_new1, meadian_profit):
     median_profit= revenues_stories_new1* surplus_margin_new1
     return median_profit      
    
'''

from inspect import getmembers, isfunction, getfullargspec
import importlib

import tempfile
import os

dirname, basename = os.path.split(__file__)
with tempfile.NamedTemporaryFile(dir=dirname, delete=True) as temp_file:
    file_name = temp_file.name + ".py"
    with open(file_name, "w") as f:
        f.write(text)
    file_name_actual = file_name.split("/")[-1][:-3]
    mod = importlib.import_module(f"{file_name_actual}")
    split_table1, split_table_2 = dict(), dict()
    for fun_name, fun_obj in getmembers(mod, isfunction):
        split_table1[fun_name] = fun_obj
        split_table_2[fun_name] = getfullargspec(fun_obj).args
    print(split_table1, split_table_2)
# {'function_cal': <function function_cal at 0x10500af70>, 'function_cal_new': <function function_cal_new at 0x10500c0d0>, 'function_cal_new1': <function function_cal_new1 at 0x10500c160>} {'function_cal': ['revenues_shops', 'surplus_margin', 'meadian_profit'], 'function_cal_new': ['revenues_stories_new', 'surplus_margin_new', 'meadian_profit'], 'function_cal_new1': ['revenues_stories_new1', 'surplus_margin_new1', 'meadian_profit']}
Deepak Tripathi
  • 3,175
  • 1
  • 8
  • 21
1

This should work:

import re

text = '''

def function_cal(revenues_shops, surplus_margin, meadian_profit):
     median_profit= revenues_shops* surplus_margin
     return median_profit
 
def function_cal_new (revenues_stories_new, surplus_margin_new, meadian_profit):
     median_profit= revenues_stories_new* surplus_margin_new
     return median_profit   
 
def function_cal_new1 (revenues_stories_new1, surplus_margin_new1, meadian_profit):
     median_profit= revenues_stories_new1* surplus_margin_new1
     return median_profit      
    
'''
    
def extraction_variables(text):
    splited_table1, splited_table2 = dict(), dict()
    lines = text.split('\n')
    for line in lines:
            x = re.search(r"^def.*:$", line)
            if x is not None:
                values = x[0].split('def ')[1].split('(')
                splited_table1 = values[0]
                splited_table2 = values[1][:-2].split(', ')
                yield splited_table1, splited_table2

splited_table1, splited_table2 = zip(*extraction_variables(text))
splited_table1  
splited_table2  

Note: type(splited_table1) will be tuple. If you want a list just do: splited_table1 = list(splited_table1)

Robin Gugel
  • 853
  • 3
  • 8