How to save a formatted string? - python-3.x

I was wondering if its possible to save a formatted string in python in any way?
For example, could I create an arbitrary string like this:
s = f"This is my string. This is a {variable}"
and then save it in a csv or an SQL database for later use given that variable would always be set before loading?
I have already tried this with a CSV document and in MySQL without much luck so I concluded that this wasn't possible. Google hasn't given much of a result either.
My specific problem is that I have a large file containing hundreds of symptoms. Each symptom is a class and inherits a parent class which contains 7 base questions regarding the symptom. I would like to load a formatted string in the parent class for the sublass to load(as it inherits the parent class). An example would be something along these lines:
In Parent class:
self.question = f"Do you have a {self.symptom}?"
In Headache class:
self.symptom = "headache"
would be parsed to the string: "Do you have a headache?" etc.
I would really like to load the questions from a database for maintainance purposes since maintaining a large .py file with large number of classes, each with a question in a string format would end up as a total nightmare.
Thanks!
Edit: spelling

I have a quick idea, but I wouldn't recommend it:
Storing it into a string, to execute it:
self.generatequestion = 'question1=f"Do you have a {self.symptom}?"'
in Headache:
self.symptom = "headache"
And then
exec(self.generatequestion1)
print(question1)

Related

Need Help creating class hierarchy in Python

I have a hierarchy of data that i would like to build using classes instead of hard coding it in. The structure is like so:
Unit (has name, abbreviation, subsystems[5 different types of subsystems])
Subsystem ( has type, block diagram(photo), ParameterModel[20 different sets of parameterModels])
ParameterModel (30 or so parameters that will have [parameter name, value, units, and model index])
I'm not sure how to do this using classes but what i have made kindof work so far is creating nested dictionaries.
{'Unit':{'Unit1':{'Subsystem':{'Generator':{Parameter:{'Name': param1, 'Value':1, 'Units': 'seconds'}
like this but with 10-15 units and 5-6 subsystems and 30 or so parameters per subsystem. I know using dictionaries is not the best way to go about it but i cannot figure out the class sharing structure or where to start on building the class structure.
I want to be able to create, read, update and delete, parameters in a tkinter gui that i have built as well as export/import these system parameters and do calculations on them. I can handle the calculations and the import export but i need to create classes that will build out this structure and be able to reference each individual unit/subsystem/parameter/value/etc
I know thats alot but any advice? ive been looking into the factory and abstract factory patterns in hope to try and figure out how to create the code structure but to no avail. I have experience with matlab, visual basic, c++, and various arduio projects so i know most basic programming but this inheritance class structure is something i cannot figure out how to do in an abstract way without hardcoding each parameter with giant names like Unit1_Generator_parameterName_parameter = ____ and i really dont want to do that.
Thanks,
-A
EDIT: Here is one way I've done the implementation using a dictionary but i would like to do this using a class that can take a list and make a bunch of empty attributes and have those be editable/callable generally like setParamValue(unit, susystem, param) where i can pass the unit the subsystem and then the parameter such as 'Td' and then be able to change the value of the key,value pair within this hierarchy.
def create_keys(list):
dict = {key: None for key in list}
return dict
unit_list = ['FL','ES','NN','SF','CC','HD','ND','TH'] #unit abbreviation
sub_list = ['Gen','Gov','Exc','PSS','Rel','BlkD']
params_GENROU = ["T'do","T''do","T'qo","T''qo",'H','D','Xd','Xq',"Xd'","Xq'","X''d=X''q",'Xl','S(1.0)','S(1.2)','Ra'] #parameter names
dict = create_keys(unit_list)
for key in dict:
dict[key] = create_keys(sub_list)
dict[key]['Gen'] = create_keys(params_GENROU)
and inside each dict[unit][Gen][ParamNames] there should be a dict containing Value, units(seconds,degrees,etc), description and CON(#basically in index for another program we use)

Is it possible to split array in Gherkin to the next line

I have step where I am have String Array, something like this:
Then Drop-dow patient_breed contains ['Breed1', 'Breed2',.... Breed20']
I need to split this text on two lines. I know that in Gherkin there is expression """. I try something like this:
Then Drop-dow patient_breed contains ['Breed1',
"""
'Breed2',.... Breed20']
"""
It didn't help. Is there any solution?
What do you gain by putting this string in your scenario. IMO all you are doing is making the scenario harder to read!
What do you lose by putting this string in your scenario?
Well first of all you now have to have at least two things the determine the exact contents of the string, the thing in the application that creates it and the hardcoded string in your scenario. So you are repeating yourself.
In addition you've increased the cost of change. Lets say we want our strings to change from 'Breedx' to 'Breed: x'. Now you have to change every scenario that looks at the drop down. This will take much much longer than changing the code.
So what can you do instead?
Change your scenario step so that it becomes Then I should see the patient breeds and delegate the HOW of the presentation of the breeds and even the sort of control that the breeds are presented in to something that is outside of Cucumber e.g. a helper method called by a step definition, or perhaps even something in your codebase.
Try with a datatable approach. You will have to add a DataTable argument in the stepdefinition.
Then Drop-dow patient_breed contains
'Breed1'
'Breed2'
...
...
...
'Breed20']
For a multiline approach try the below. In this you will have to add a String argument to the stepdefinition.
Then Drop-dow patient_breed contains
"""
['Breed1','Breed2',.... Breed20']
"""
I would read the entire string and then split it using Java after it has been passed into the step. In order to keep my step as a one or two liner, I would use a helper method that I implemented myself.

In IDL, how can I access a variable given its name?

I would like to convert a string to a variablename, so it can be read as a already restored variable.
So, I look through a file, and look at all the files. I use RESTORE to use the file in IDL, restore names this object as something slightly different. It names it as an object which we'll call map_1 (in the code it's called filerestore_name). This is related to the file name and I can recreate this variable name - however, its saved as a string.
Now, I pass this onto the make_cool_video procedure. However, althoughthis string now is exactly the same as the varialbe name, its still a string!.
Thus, as its a string, the procedure can't work.
filenames=FILE_SEARCH('rxrt*')
filenames_withoutextension = STREGEX(filenames,'rxrt_[0-9]+[a-zA-Z_]+',/EXTRACT,/FOLD_CASE)
restore, '/home/tomi/Documents/actualwork/'+filenames_withoutextension(18)+'.idl_sav',
filerestore_name = STRJOIN(STRSPLIT(filenameswithout(18),'_[0-9]+',/EXTRACT,/REGEX),'')
PRINT, filerestorename
make_cool_video, EXECUTE(filerestore_name),filename=filerestorenames, outdir='/path/to.file/'
retall
What I tried: using the RESTORE function and the associated RESTORED_OBJECTS to store pointers in an array, and then referring to the array. But I couldn't get the restore function to form an array.
Using EXECUTE(filerestore_name) however, this doesn't convert it as I was expecting.
I would recommend using SCOPE_VARFETCH() instead (it isn't as limited as EXECUTE() and is probably more efficient). You can do something like:
make_cool_video, (SCOPE_VARFETCH(filerestore_name)), filename=filerestorenames, outdir='/path/to.file/'
I wrote this, then immediately thought of the answer.
So,
Convert everything to a string:
string1 = "makecooljes, "+ filerestore_name, outdir='file/to/path/'"
result= EXECUTE(string1)

How to compare Strings and put it into another program?

i´ve got small problem and before I spend even more time in trying to solve it i´d like to know if what I want to do is even possible ( and maybe input on how to do it^^).
My problem:
I want to take some text and then split it into different strings at every whitespace (for example "Hello my name is whatever" into "Hello" "my" "name" "is" "whatever").
Then I want to set every string with it´s own variable so that I get something alike to a= "Hello" b= "my" and so on. Then I want to compare the strings with other strings (the idea is to get addresses from applications without having to search through them so I thought I could copy a telephone book to define names and so on) and set matching input to variables like Firstname , LastName and street.
Then, and here comes the "I´d like to know if it´s possible" part I want it to put it into our database, this means I want it to copy the string into a text field and then to go to the next field via tab. I´ve done something like this before with AutoIT but i´ve got no idea how to tell AutoIT whats inside the strings so I guess it must be done through the programm itself.
I´ve got a little bit of experience with c++, python and BATCH files so it would be nice if anyone could tell me if this can even be done using those languages (and I fear C++ can do it and I´m just to stupid to do so).
Thanks in advance.
Splitting a string is very simple, there is usually a built in method called .split() which will help you, the method varies from language to language.
When you've done a split, it will be assigned to an array, you can then use an index to get the variables, for example you'd have:
var str = "Hello, my name is Bob";
var split = str.split(" ");
print split[0]; // is "Hello,"
print split[1]; // is "my" etc
You can also use JSON to return data so you could have an output like
print split["LastName"];
What you're asking for is defiantly possible.
Some links that could be useful:
Split a string in C++?
https://code.google.com/p/cpp-json/

Groovy says my Unicode string is too long

As part of my probably wrong and cumbersome solution to print out a form I have taken a MS-Word document, saved as XML and I'm trying to store that XML as a groovy string so that I can ${fillOutTheFormProgrammatically}
However, with MS-Word documents being as large as they are, the String is 113100 unicode characters and Groovy says its limited to 65536. Is there some way to change this or am I stuck with splitting up the string?
Groovy - need to make a printable form
That's what I'm trying to do.
Update: to be clear its too long of a Groovy String.. I think a regular string might be all good. Going to change strategy and put some strings in the file I can easily find like %!%variable_name%!% and then do .replace(... uh i feel a new question coming on here...
Are you embedding this string directly in your groovy code? The jvm itself has a limit on the length of string constants, see the VM Spec if you are interested in details.
A ugly workaround might be to split the string in smaller parts and concatenate them at runtime. A better solution would be to save the text in an external file and read the contents from your code. You could also package this file along with your code and access it from the classpath using Class#getResourceAsStream.

Resources