Write Float in File Python3, without Converting it into String - python-3.x

I am trying to use loop to write float into a file, but the write function does not let it happen until I convert it into string or use format, which eventually converts it into string.
Is there any way that I can do it? I need the data inside the file to be in float, since later on the file data can be used to create graphs, thus strings can not be a way out.
Later on I need to use Termgraph Python3 library for this, and the data needs to be a float.
print("sequence","Sign","Values")
f = open("termdata.dat","w")
f.write("Sequence,Score\n")
for i in range(0,len(list_one)):
value1 = list_two[i]
value_ = q_score[value1]
print(list_one[i],"\t", list_two[i],"\t", value_)
str1 = str(list_one[i])
float1 = float(value_)
f.write(str1)
f.write(",")
f.write(str(float1))
f.write("\n")

Related

Reading a comma-separated string (not text file) in Matlab

I want to read a string in Matlab (not an external text file) which has numerical values separated by commas, such as
a = {'1,2,3'}
and I'd like to store it in a vector as numbers. Is there any function which does that? I only find processes and functions used to do that with text files.
I think you're looking for sscanf
A = sscanf(str,formatSpec) reads data from str, converts it according
to the format specified by formatSpec, and returns the results in an
array. str is either a character array or a string scalar.
You can try the str2num function:
vec = str2num('1,2,3')
If you have to use the cell a, per your example, it would be: vec=str2num(a{1})
There are some security warnings in the documentation to consider so be cognizant of how your code is being employed.
Another, more flexible, option is textscan. It can handle strings as well as file handles.
Here's an example:
cellResult = textscan('1,2,3', '%f','delimiter',',');
vec = cellResult{1};
I will use the eval function to "evaluate" the vector. If that is the structure, I will also use the cell2mat to get the '1,2,3' text (this can be approached by other methods too.
% Generate the variable "a" that contains the "vector"
a = {'1,2,3'};
% Generate the vector using the eval function
myVector = eval(['[' cell2mat(a) ']']);
Let me know if this solution works for you

How to convert a variable to a raw string?

If I have a string, "foo; \n", I can turn this into a raw string with r"foo; \n". If I have a variable x = "foo; \n", how do I convert x into a raw string? I tried y = rf"{x}" but this did not work.
Motivation:
I have a python string variable, res. I compute res as
big_string = """foo; ${bar}"""
from string import Template
t = Template(big_string)
res = t.substitute(bar="baz")
As such, res is a variable. I'd like to convert this variable into a raw string. The reason is I am going to POST it as JSON, but I am getting json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 620 (char 619). Previously, when testing I fixed this by converting my string to a raw string with: x = r"""foo; baz""" (keeping in line with the example above). Now I am not dealing with a big raw string. I am dealing with a variable that is a JSON representation of a string where I have replaced a single variable, bar above, with a list for a query, and now I want to convert this string into a raw string (e.g. r"foo; baz", yes I realize this is not valid JSON).
Update: As per this question I need a raw string. The question and answer flagged in the comments as duplicate do not work (res.encode('unicode_escape')).

Properly write into string in Matlab (efficient and preserving escape characters)

I have an abstract class Writer which allows clients to write into something. Could be the screen, could be a file. Now, I try to create a derived class to write into a string.
I have two problems with the denoted line in method write(...):
It's probably very inefficient. Is there something like a string buffer in Matlab?
It writes escape sequences like \n plain into the string, instead of taking their actual meaning.
How can I get the denoted line properly?
Code:
classdef StringTextWriter < Writer
properties
str;
end
methods
function this = StringTextWriter()
% Init the write-target which is a string in our case.
% (Other Writer classes would maybe open a file.)
this.str = '';
end
function write(this, val)
% Write to writer target.
% (Other Writer classes would maybe use fprinf here for file write.)
% ?????????????????????????????
this.str = [this.str val]; % How to do this properly?
% ?????????????????????????????
end
end
end
To answer your questions point by point:
The closest notion to a string buffer would be a string cell. Instead of:
str = '';
str = [strbuf, 'abc\n'];
str = [strbuf, 'def\n'];
str = [strbuf, 'ghi\n'];
%// and so on...
one may use
strbuf = {};
strbuf{end+1} = 'abc\n';
strbuf{end+1} = 'def\n';
strbuf{end+1} = 'ghi\n';
%// and so on...
str = sprintf([strbuf{:}]); %// careful about percent signs and single quotes in string
the drawback being that you have to reconstruct the string every time you ask for it. This can be alleviated by setting a modified flag every time you add strings to the end of strbuf, resetting it every time you concatenate the strings, and memoizing the result of concatenation in the last line (rebuild if modified, or last result if not).
Further improvement can be achieved by choosing a better strategy for growing the strbuf cell array; probably this would be effective if you have a lot of write method calls.
The escape sequences are really linked to the <?>printf family and not to the string literals, so MATLAB in general doesn't care about them, but sprintf in particular might.

How do I parse a string into a record in Haskell?

In C, reading the data in a string and putting its data into a struct is fairly straight forward, you just use something along the lines of sscanf to parse your data:
struct ingredient_dose ingr;
char *current_amount = "5 tsp sugar";
sscanf(current_amount, "%d %s %s", &ingr.amount, ingr.unit, ingr.ingredient);
Which would fill the struct/record with the given data.
How would I do something similar in Haskell? I realise you can't mutate anything once it's made, so the procedure will obviously be a bit different from the C example, but I can't seem to find a decent guide that doesn't include parsing JSON.
Haskell doesn't have any built-in function which does exactly what scanf does.
However, if your stuff is space-delimited, you could easily use words to split the string into chunks, and the read function to convert each substring into an Int or whatever.
parse :: String -> (Int, String, String)
parse txt =
let [txt1, txt2, txt2] = words txt
in (read txt1, txt2, txt3)
What Haskell does have an abundance of is "real" parser construction libraries, for parsing complex stuff like... well... JSON. (Or indeed any other computer language.) So if your input is more complicated than this, learning a parser library is typically the way to go.
Edit: If you have something like
data IngredientDose = IngredientDose {amount :: Double, unit, ingredient :: String}
then you can do
parse :: String -> IngredientDose
parse txt =
let [txt1, txt2, txt2] = words txt
in IngredientDose {amount = read txt1, unit = txt2, ingredient = txt3}

MATLAB: Convert string to number and then back to string

There is a string containing a number in an arbitrary format (e.g., 12, -34.5, and 6.78e-9). The goal is to convert this string into the corresponding number and then convert this number back to a string such that (a) the precision given in the original string is preserved, and (b) the resulting string has an adequate format (probably, the most adequate format is the format of the original string). I thought the problem could be easily solved using str2num and num2str; however, in some cases, MATLAB seems to be mangling the final result as shown below:
>> a = '1e23'
a =
1e23
>> b = str2num(a)
b =
1.0000e+23
>> c = num2str(b)
c =
9.999999999999999e+22
One solution is to use a general format string:
>> c = num2str(b, '%e')
c =
1.000000e+23
However, in this case, the output looks rather cumbersome for numbers of small orders:
>> d = num2str(1, '%e')
d =
1.000000e+00
In most cases, num2str without additional parameters does a pretty good job resulting in a nicely formatted string. The question is: Is there a way to eliminate the 9.999999999999999e+22 problem?
Thank you!
Regards,
Ivan
In general the representation of one input string does not contain enough information to determine the format. Hence (assuming you want to output slightly different numbers and cannot simply store the number in string format), the simplest way would be to try and find a format that you like.
Judging from your comments, I think you will be happy with:
format short g
For large numbers it will give:
x = num2str(1.0000e+23);str2num(x)
ans =
1e+23
And for small numbers:
x = num2str(1);str2num(x)
ans =
1

Resources