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.