Writing txt-file float - python

Now I have this kind of code:
for s,h,v,r in zip(lopullinen, yksilo, osallistumiset, pistemaarat):
tulostuksia.write(str(s) + ";".join(h) + ";" + str(r) + ";" + ";".join(str(v)) + "/7" + "\n")
and it gives this kind of output:
tunnus;nimi;sarja;juoksu-60m;pituushyppy;kuulantyonto;korkeushyppy;aitajuoksu-60m;seivashyppy;juoksu-1000m;kokonaispisteet;lajeja
101;Vertti Veteraaniurheilija;M70;709;651;750;806;850;759;801;5326;7/7
41;Severi Seitsenottelija;M;603;551;600;555;559;655;700;4223;7/7
42;Seppo Seitsenottelija;M;661;750;700;610;505;502;700;4428;7/7
43;Ylermi Yleisurheilija;M;603;601;700;655;661;555;500;4275;7/7
60;K. Keskeyttäjä;M40;603;601;-;-;-;-;-;1204;2/7
61;Yrjänä Yleisurheilija;M40;559;500;650;701;603;655;650;4318;7/7
But I would like to have those numbers to be float-types. Like this:
101;Vertti Veteraaniurheilija;M70;709.0;651.0;750.0;806.0;850.0;759.0;801.0;5326;7/7
Thouse numbers come from the list yksilo, which contains numbers from class. If i change it there to be float(when adding to the list), and from that for loop above ";".join(str(h)). It gives me output where the ";" is between every number(7;0;9;.;0; etc...) And if i don't put the str(h) in there, it gives "TypeError: sequence item 0: expected str instance, float found".
Is there an easy way to get those numbers to be formed 709.0 instead of 709.

Use
'%f' % value
instead of the simple
str(value)
But the str(value) should already have given you '4.0' if the value had been a float in the beginning. So maybe you need to convert that value to a float first:
str(float(value))
Also, if you need to keep the - values, you will have to check for these as well. So in your example, use
tulostuksia.write(
'%s%s;%s;%s%s' % (
s,
";".join(h),
r,
";".join('-' if vi == 'i' else str(float(vi)) for vi in v),
"/7\n")

If h is a list [709.0, 651.0] then str(h) gives you "[709.0, 651.0]" and ';'.join(str(h)), as you've seen, will iterate over the characters in the string, rather than the values in the list.
Instead, try ';'.join(map(str, h)). This converts each item in the list individually to a string (whether it's a '-' or a float), then joins the resulting iterable/list (depending on Python version) of strings.
Example:
>>> print(";".join(map(str, ["-", 123.4, 567.8, "-", "-", 9.0])))
-;123.4;567.8;-;-;9.0

Related

Get selected node names into a list or tuple in Nuke with Python

I am trying to obtain a list of the names of selected nodes with Python in Nuke.
I have tried:
for s in nuke.selectedNodes():
n = s['name'].value()
print n
This gives me the names of the selected nodes, but as separate strings.
There is nothing I can do to them that will combine each string. If I
have three Merges selected, in the Nuke script editor I get:
Result: Merge3
Merge2
Merge1
If I wrap the last variable n in brackets, I get:
Result: ['Merge3']
['Merge2']
['Merge1']
That's how I know they are separate strings. I found one other way to
return selected nodes. I used:
s = nuke.tcl("selected_nodes")
print s
I get odd names back like node3a7c000, but these names work in anything
that calls a node, like nuke.toNode() and they are all on one line. I
tried to force these results into a list or a tuple, like so:
s = nuke.tcl("selected_nodes")
print s
Result: node3a7c000 node3a7c400 node3a7c800
s = nuke.tcl("selected_nodes")
s2 = s.replace(" ","', '")
s3 = "(" + "'" + s2 + "'" + ")"
print s3
Result: ('node3a7c000', 'node3a7c400', 'node3a7c800')
My result looks to have the standard construct of a tuple, but if I try
to call the first value from the tuple, I get a parentheses back. This
is as if my created tuple is still a string.
Is there anything I can do to gather a list or tuple of selected nodes
names? I'm not sure what I am doing wrong and it seems that my last
solution should have worked.
As you iterate over each node, you'll want to add its name to a list ([]), and then return that. For instance:
names = []
for s in nuke.selectedNodes():
n = s['name'].value()
names.append(n)
print names
This will give you:
# Result: ['Merge3', 'Merge2', 'Merge1']
If you're familiar with list comprehensions, you can also use one to make names in one line:
names = [s['name'].value() for s in nuke.selectedNodes()]
nodename = list()
for node in nuke.selectedNodes():
nodename.append(node.name())

% operator on chars and event handling in tkinter

While reading about event handling with Tkinter, I found out the piece of code below.
Can somebody explain to me what is the purpose of the modulo operator here and how it works, assuming the following declaration of show_event_details function:
def show_event_details(event):
event_name = {"2": "KeyPress", "4": "ButtonPress", "6": "Motion", "9":"FocusIn"}
print ('='*50)
print ("EventName=" + event_name[str(event.type)])
print ("EventKeySymbol=" + str(event.keysym))
print ("EventType=" + str(event.type))
print ("EventWidgetId=" + str(event.widget))
print ("EventCoordinate (x,y)=(" + str(event.x)+","+str(event.y)+")")
print ("Time:", str(event.time))
The code:
alphanum = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789'
for i in alphanum:
mye.bind("<KeyPress-%s>"%i, show_event_details)
keysyms = ['Alt_L', 'Alt_R','BackSpace', 'Cancel', 'Caps_Lock','Control_L',
'Control_R','Delete', 'Down', 'End', 'Escape', 'Execute','F1',
'F2', 'Home', 'Insert', 'Left','Linefeed','KP_0','KP_1','KP_2',
'KP_3','KP_4','KP_5','KP_6','KP_7','KP_8','KP_9','KP_Add',
'KP_Decimal','KP_Divide']
for i in keysyms:
mye.bind("<KeyPress-%s>"%i, show_event_details)
In the code block you have, the % operator is being used to format the string. If you notice, the following line:
mye.bind("<KeyPress-%s>"%i, show_event_details)
Has "%s inside the string, and the % operator afterwards. This is essentially telling Python that it will be given an argument, which should be converted into a string and placed there.
It is a convenient way of representing variables in strings with different presentations. In this case, it is converting the variable "i" to a string.
% doubles as a string-formatting operator. The expression
"<KeyPress-%s>" % i
evaluates to a string in which %s is replaced by the value of i. (This explanation glosses over a few details, such as why %s is used and how things change if the right-hand operand of % is a tuple instead of a single value. See the documentation for more information.)

String indices must be integers, new to python

I hope I won't get trashed for this question. This is my first day with Python and all I've done so far is copy pasting and deducing from other snippets of code. I have no experience with code. I'm trying my hardest however this one I can't get past for the past few hours.
I'm currently adjusting an Editorial (iOS app) workflow to fit my needs — namely: posting to my WordPress site, including the ability to choose from a list of all possible post formats (I have "standard" and "link" enabled).
Here is the faulty bit from the relevant Python script:
console.show_activity('Fetching formats...')
server = xmlrpclib.ServerProxy(wp_url)
format = server.wp.getPostFormats(wp_blogid, wp_username, wp_password, 'post_format')
i = 0
for x in format:
formats += '\n' + x['name'] + " " + str(i)
i = i+1
workflow.set_variable("formats", formats)
console.hide_activity()
I'm getting the error: "string indices must be integers, not str"
What is this supposed to do is later show me in a list my available formats. I've done this successfully with server.wp.getPostFormats(wp_blogid, wp_username, wp_password, 'post_tag') and server.wp.getTerms(wp_blogid, wp_username, wp_password, 'category')
I know my problem is where the line with the i starts, I just have no idea how to solve it. I'm assuming by reading other topics that I need to cast, but I'm not even sure what getPostFormats returns, or how to do that.
Thanks in advance!
Edit: I've now concluded that server.wp.getPostFormats returns a dictionary, but I have not a slightest idea on how to retrieve only one set of data (either the key or value) of this dictionary. Please help.
You're getting that error because "string indices must be integers, not str".
formats += '\n' + x['name'] + " " + str(i)
Here, you are accessing the 'name'th element of x, where 'name' is of course a string and x is a string too, since server.wp.getPostFormats obviously returns a list of strings.
So simply look at format and you should immediately see how to obtain the required data.
UPDATE:
OK, so you figured out that format is a dictionary (returned from server.wp.getPostFormats). In Python, if you iterate over a dictionary (your for-loop), you iterate through its keys. This is the standard behaviour.
Look at this example:
>>> foo = {'a': 1, 'c': 3, 'b': 2}
>>> for x in foo: print(x)
...
a
c
b
Of course you also need the values, not only the keys (you seem to look for an entry with the key name). One way is to iterate though the keys and items in one shot:
>>> for key, value in foo.iteritems():
... print(key + ":" + str(value))
...
a:1
c:3
b:2
So the .iteritems() method of a dictionary returns for every iteration a key/value-pair, which you can unpack within the for loops definition.
In your case, you can do the following:
for key, value in format.iteritems():
formats += 'key: ' + key + ', value: ' + value + '\n'
Given that you are new, I would also suggest using the enumerate method and refactoring your code:
for i, x in enumerate(format):
formats += '\n' + x[idx_for_name] + " " + str(i)
The idx_for_name would be the index for the name.
If you wanna go even further, you can use the join method too:
formats = '\n'.join(x[idx_for_name] + " " + str(i) \
for i, x in enumerate(format))
warning: This code is untested.
Read:
http://python-wordpress-xmlrpc.readthedocs.org/en/latest/ref/methods.html#wordpress_xmlrpc.methods.posts.GetPostFormats
GetPostFormats return a dictionary so x iterates among the keys which are strings.
Try:
x= format['all']:

can't convert string to integer-python

I have a string within a tuple like this:
params': {
'rtinseconds': '57.132',
**'charge': '3+'**,
'pepmass': (822.6547241, None),
title': '20130630_006.d, MS/MS of 822.6547241 3+ at 0.9522 mins'
}
I am trying to read and convert the value of charge '3+' to integer value 3.
I tried the following code where I read the first character in the string and stored it in a separate variable, then tried to convert it to int, but does not work. The type of 3 is still str. Does anyone have any suggestions?
temp_z = item['params']['charge']
z = temp_z[0:1]
str(z)
int(z)
In the simple case:
z = int(params['charge'].replace('+',''))
However if it is possible that your item may have a negative charge you may want:
if '+' in params['charge']:
z = int(params['charge'].replace('+',''))
else:
z = -int(params['charge'].replace('-',''))

PYTHON problem with negative decimals

I have a list of negative floats. I want to make a histogram with them. As far as I know, Python can't do operations with negative numbers. Is this correct? The list is like [-0.2923998, -1.2394875, -0.23086493, etc.]. I'm trying to find the maximum and minimum number so I can find out what the range is. My code is giving an error:
setrange = float(maxv) - float(minv)
TypeError: float() argument must be a string or a number
And this is the code:
f = open('clusters_scores.out','r')
#first, extract all of the sim values
val = []
for line in f:
lineval = line.split()
print lineval
val.append(lineval)
print val
#val = map(float,val)
maxv = max(val)
minv = min(val)
setrange = float(maxv) - float(minv)
All the values that are being put into the 'val' list are negative decimals. What is the error referring to, and how do I fix it?
The input file looks like:
-0.0783532095182 -0.99415440702 -0.692972552716 -0.639273674023 -0.733029194040.765257900121 -0.755438339963
-0.144140594077 -1.06533353638 -0.366278118372 -0.746931508538 -1.02549039392 -0.296715961215
-0.0915937502791 -1.68680560936 -0.955147543358
-0.0488457137771 -0.0943080192383 -0.747534412969 -1.00491121699
-1.43973471463
-0.0642611118901 -0.0910684525497
-1.19327387414 -0.0794696449245
-1.00791366035 -0.0509749096549
-1.08046507281 -0.957339914505 -0.861495748259
The results of split() are a list of split values, which is probably why you are getting that error.
For example, if you do '-0.2'.split(), you get back a list with a single value ['-0.2'].
EDIT: Aha! With your input file provided, it looks like this is the problem: -0.733029194040.765257900121. I think you mean to make that two separate floats?
Assuming a corrected file like this:
-0.0783532095182 -0.99415440702 -0.692972552716 -0.639273674023 -0.733029194040 -0.765257900121 -0.755438339963
-0.144140594077 -1.06533353638 -0.366278118372 -0.746931508538 -1.02549039392 -0.296715961215
-0.0915937502791 -1.68680560936 -0.955147543358
-0.0488457137771 -0.0943080192383 -0.747534412969 -1.00491121699
-1.43973471463
-0.0642611118901 -0.0910684525497
-1.19327387414 -0.0794696449245
-1.00791366035 -0.0509749096549
-1.08046507281 -0.957339914505 -0.861495748259
The following code will no longer throw that exception:
f = open('clusters_scores.out','r')
#first, extract all of the sim values
val = []
for line in f:
linevals = line.split()
print linevals
val += linevals
print val
val = map(float, val)
maxv = max(val)
minv = min(val)
setrange = float(maxv) - float(minv)
I have changed it to take the list result from split() and concatenate it to the list, rather than append it, which will work provided there are valid inputs in your file.
All the values that are being put into the 'val' list are negative decimals.
No, they aren't; they're lists of strings that represent negative decimals, since the .split() call produces a list. maxv and minv are lists of strings, which can't be fed to float().
What is the error referring to, and how do I fix it?
It's referring to the fact that the contents of val aren't what you think they are. The first step in debugging is to verify your assumptions. If you try this code out at the REPL, then you could inspect the contents of maxv and minv and notice that you have lists of strings rather than the expected strings.
I assume you want to put all the lists of strings (from each line of the file) together into a single list of strings. Use val.extend(lineval) rather than val.append(lineval).
That said, you'll still want to map the strings into floats before calling max or min because otherwise you will be comparing the strings as strings rather than floats. (It might well work, but explicit is better than implicit.)
Simpler yet, just read the entire file at once and split it; .split() without arguments splits on whitespace, and a newline is whitespace. You can also do the mapping at the same point as the reading, with careful application of a list comprehension. I would write:
with open('clusters_scores.out') as f:
val = [float(x) for x in f.read().split()]
result = max(val) - min(val)

Categories

Resources