Home > Mobile >  Arrange and store text from function
Arrange and store text from function

Time:10-11

I am trying to extract and arrange some words from a specific text.

text = '''
def function_cal(revenues_shops, surplus_margin, meadian_profit):
     meadian_profit= revenues_shops* surplus_margin
     return meadian_profit
'''

# Extract names
lines = text.split('\n')
for line in lines:
  x = re.search(r"^def.*:$", line)
  if x != None:
      values = x[0].split('def ')[1].split('(')
      function_name = values[0]
      arguments = values[1][:-2].split(', ')

      print(f"Function Name: {function_name}")
      print(f"Arguments: {arguments}")

The code is shown above functioning well and produce good results with the command for print. Now I want to store all of these results in separate files (e.g data frames, dictionaries, etc.) because I want to use these results for further analysis.

Can anybody help me how to solve this?

I tried with those lines described below but is not working

    # Create 
    splited_table1= dict() 
    splited_table2= dict() 
        
    # Extract 
    def extraction_variables(text):
      lines = text.split('\n')
      for line in lines:
        x = re.search(r"^def.*:$", line)
        if x != None:
            values = x[0].split('def ')[1].split('(')
            splited_table1 = values[0]
            splited_table2 = values[1][:-2].split(', ')
            return splited_table1, splited_table2


extraction_variables(text)
    
    splited_table1.sort()
    splited_table2.sort()

CodePudding user response:

As I mentioned in my comment above, you've not used the value returned from inside the extraction_variables function. To do so, your code would look something like:

import re

text = '''
def function_cal(revenues_shops, surplus_margin, meadian_profit):
     meadian_profit= revenues_shops* surplus_margin
     return meadian_profit
'''


def extraction_variables(text):
    # initialize the return variables *inside* the function
    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  # => 'function_cal'
splited_table2  # => ['revenues_shops', 'surplus_margin', 'meadian_profit']
  • Related