Home > Mobile >  Python script to process some data from one file and write output in another one
Python script to process some data from one file and write output in another one

Time:08-25

I am completely new to Python and I would like to know how to process some data from one file and write the output to another one, using a python script.

inputFile.txt is

// * * * * * * * * * *   geometry  * * * * * * * * * * * //
// domain start point in meters
X0                  0;
Y0                  0;
Z0                  0;

// full lenght, widht, height of domain in meters
Ld                  60;
Wd                  4;
Hd                  8;

// specific lenght, height, start of slope 1 in meters
Ls1                 5;
Hs1                 2;
Xs1                 40;

// specific lenght, height of slope 2 in meters
Ls2                 15;
Hs2                 3;

outputFile.txt would contain the results of

X0  Y0  Z0
X0 Ld-Ls1-Ls2    Y0    Z0
X0 Ld-Ls2    Y0    Z0 Hs1
X0 Ld    Y0    Z0 Hs1 Hs2
X0 Ld    Y0    Z0 Hd
X0    Y0    Z0 Hd

which means outputFile.txt would be

0 0 0
40 0 0
45 0 2
60 0 5
60 0 8
0 0 8

How to script this ?

Many thanks in advance for your help

CodePudding user response:

You need to read and parse your input file to store the variables, then you need to parse, evaluate, and write to file an output format so you get your desired output.

He's a short but very delicate and unsafe (it uses eval to do the evaluating) implementation. Definitely not to be used for anything serious.

output_format = (r"""X0  Y0  Z0
X0 Ld-Ls1-Ls2    Y0    Z0
X0 Ld-Ls2    Y0    Z0 Hs1
X0 Ld    Y0    Z0 Hs1 Hs2
X0 Ld    Y0    Z0 Hd
X0    Y0    Z0 Hd""".splitlines())

# The parsed variables and their values will be stored in a dict
# e.g. variables["X0"] returns "0"
variables = {}

# Parse the input file
with open("inputFile.txt") as f:
    for line in f:
        line = line.strip()
        
        # Skip comments and empty lines
        if line.startswith("//") or not line:
            continue
        
        key, value = line.split(maxsplit=2)
        variables[key] = value.replace(";", "")

# Each evaluated line will be stored in a list
evaluated_lines = []

# Parse the output format string line by line
for line in output_format:
    expressions = line.split()
    
    # Each evaluated expression will be stored in a list, and resets every line
    results = []
    
    # Tokenise and evaluate each expression
    # It assumes variables must start with an alphabetic character
    # Variables are immediately replaced with their values from the variable dict
    for expression in expressions:
        tokens = []
        is_variable = False
        
        # Used to store the previous characters that make up a variable name
        chars = []
        for char in expression:
            if char in {" ", "-"}:
                tokens.append(variables["".join(chars)])
                chars = []
                tokens.append(char)
                is_variable = False
            elif is_variable or char.isalpha():
                is_variable = True
                chars.append(char)
        
        if chars:
            tokens.append(variables["".join(chars)])
        
        # Use eval to evaluate the expression
        results.append(eval("".join(tokens)))
    
    # Now the entire line has been parsed and evaluated, add it to the list
    evaluated_lines.append(" ".join(str(result) for result in results))

# Write the evaluated lines to file, separated by a new line
with open("outputFile.txt", "w") as f:
    f.write("\n".join(evaluated_lines))

inputFile.txt:

// * * * * * * * * * *   geometry  * * * * * * * * * * * //
// domain start point in meters
X0                  0;
Y0                  0;
Z0                  0;

// full lenght, widht, height of domain in meters
Ld                  60;
Wd                  4;
Hd                  8;

// specific lenght, height, start of slope 1 in meters
Ls1                 5;
Hs1                 2;
Xs1                 40;

// specific lenght, height of slope 2 in meters
Ls2                 15;
Hs2                 3;

outputFile.txt:

0 0 0
40 0 0
45 0 2
60 0 5
60 0 8
0 0 8

I think what you want to achieve is too difficult to understand if you're new to Python, unless you've previously written a parser in another language.

CodePudding user response:

I would use some regex.

This is my suggested approach:

import os
import re
import csv


if __name__ == "__main__":

    curPath = os.path.dirname(os.path.realpath(__file__))
    
    # Open the input file
    with open(os.path.join(curPath,'inputFile.txt'), 'r') as inputFile:
        
        data = inputFile.read()
        
        # read values and convert them
        x0 = int(re.search("X0 *([0-9.,] );",data).group(1)) # Use float() if you need!
        y0 = int(re.search("Y0 *([0-9.,] );",data).group(1))
        
        # ... and so on
        
        # Do your operations easily here
        
    # Write the final file
    with open(os.path.join(curPath,'Output.txt'), 'w') as output:    
        output.write(f"{x0} {y0} whatever...")
  • Related