Unable to iterate random values in subsequent lines in Python - python

There are probably many more straightforward ways of achieving my aim here, but as a Python newbie, I'd appreciate it if we could just concentrate on the code I'm using.
I'm attempting to write out a list of commands for a graphics program (G'MIC) and output those to a command prompt (although not directly) using Python 3.6.4 (OS: Windows 10 Pro), I need to write many lines of code but each line has to have different sets of numbers (integers and floats).. for example in the code I'm attempting to use right now the syntax is like this:
gmic v -99 input_.png fx_pastell
0.5,1,0,10,40,633,11,95,1,1,0.291651967558584,0,0,8,150,1,81,1,0,0,0 -o
out_001.png
^ all the variables denote parameters within the particular script (in this case Pastell effect).
The code I wrote relies on the Random module to get certain numbers within a range for each parameter that I want to change.
My stumbling block is to get the script to output DIFFERENT random numbers each time it prints a line. Here is my code (it's awful, I know..):
import random
a = random.randint (3,13)
b = random.randint (1,68)
c = random.randint (1,682)
d = random.randint (2,12)
e = random.randint (1,109)
g = random.randint (1,8)
h = random.uniform (0, 1)
k = random.randint (1,11)
l = random.randint (1,201)
n = random.randint (1,300)
o = random.randint (1,4)
dataFile = open("gmic1.txt", "w")
for line in range(120):
dataFile.write("gmic v -99 input_.png fx_pastell 0.5,1,0" + "," + str(a)
+ "," + str(b) + "," + str(c) + "," +str(d) + "," + str(e) + ",1," + str(g)
+ "," + str(h) + ",0,0," + str(k) + "," + str(l) + ",1," + str(n) + "," +
str(o) +"," + "0,0,0 -o out_%04d.png \n" % line)
dataFile.close()
The output is like this:
gmic v -99 input_.png fx_pastell
0.5,1,0,12,2,521,12,85,1,7,0.04003331068764937,0,0,8,17,1,297,2,0,0,0 -o
out_0000.png
gmic v -99 input_.png fx_pastell
0.5,1,0,12,2,521,12,85,1,7,0.04003331068764937,0,0,8,17,1,297,2,0,0,0 -o
out_0001.png
.. etc...
no errors as such, but not outputting a different set of numbers each time as I'd hoped.
The first input image name variable I can change with Notepad++'s Column Editor, so that takes care of that, I only need to know how to make each line of code differ.
Any help greatly appreciated!

You should call rand function on every iteration
from random import randint, uniform
dataFile = open("gmic1.txt", "w")
for line in range(120):
dataFile.write("gmic v -99 input_.png fx_pastell 0.5,1,0"
+ "," + str(randint(3, 13))
+ "," + str(randint(1, 68))
+ "," + str(randint(1, 682))
+ "," + str(randint(2, 12))
+ "," + str(randint(1, 109))
+ ",1," + str(randint(1, 8))
+ "," + str(uniform(0, 1))
+ ",0,0," + str(randint(1, 11))
+ "," + str(randint(1, 201))
+ ",1," + str(randint(1, 300))
+ "," + str(randint(1, 4))
+ "," + "0,0,0 -o out_%04d.png \n" % line)
dataFile.close()

Related

Writing measurements to a file only writes the first 10 lines

I'm trying to write certain measurements to an output file in python3, but the output file only reflects the first 10 lines
I'm using the following code to write to the file:
f = open("measurements.txt", "w")
for infile in glob.glob("./WAVs/*"):
#do some stuff with the input file
f.write(outfile.removesuffix(".wav") + "\t" + str(oldSIL) + "\t" +
str(oldSPL) + "\t" + str(oldLoud) + "\t" + str(newLoud) + "\t"+
infile.removesuffix(".wav") + "\n")
f.close()
Looking at measurements.txt I find that only the first 10 lines of the expected output have been written.
If I try to print the same lines instead of writing to a file using
print(outfile.removesuffix(".wav") + "\t" + str(oldSIL) + "\t" + str("oldSPL") + "\t" + str(oldLoud) + "\t" + str(newLoud) + "\t"+ infile.removesuffix(".wav") + "\n")
It correctly prints every single line up to the final index. I'm a little lost as to why this might be the case.

Error upon inserting excel formula from Python to excel tab

So I was asked to insert this formula to each tab in excel. Problem is caused by "=" because if I remove "=" from below code it works just fine.
I use library openpyxl
page['%s%s' % (slownik['transport cost per m3'], str(k))] = "=JEŻELI.BĄŁD(" + slownik['price per truck'] + str(k) + "/" + \
slownik['m3 per truck'] + ")" + str(k)
I got an error and excel breaks.
This below works just fine.
page['%s%s' % (slownik['transport cost per m3'], str(k))] = "JEŻELI.BĄŁD(" + slownik['price per truck'] + str(k) + "/" + \
slownik['m3 per truck'] + ")" + str(k)
Okay so. First of all formula should be done in english. Also In formula I shouldn't use
";"
I should use:","
So in the end formula inside python looks like this:
page['%s%s' % (slownik['transport cost per m3'], str(k))] = "=IFERROR(" + slownik['price per truck'] + str(k) + "/" + slownik['m3 per truck'] + str(k) + ",0)"

print statement never gets executed in a loop

in the below posted code, the first nested for loops displays the logs or the print statemnt as expected. but the latter nested for loops which has k and l as indces never displys the logs or the print statement within it.
please let me know why the print statement
print(str(x) + ",,,,,,,,,,,,,,,,,,," + str(y))
never gets displayed despite the polygonCoordinatesInEPSG25832 contains values
python code:
for feature in featuresArray:
polygonCoordinatesInEPSG4326.append(WebServices.fetchCoordinateForForFeature(feature))
for i in range(len(polygonCoordinatesInEPSG4326)):
for j in range(len(polygonCoordinatesInEPSG4326[i])):
lon = polygonCoordinatesInEPSG4326[i][j][0]
lat = polygonCoordinatesInEPSG4326[i][j][1]
x, y = transform(inputProj, outputProj, lon, lat)
xy.append([x,y])
print ("lon:" + str(lon) + "," + "lat:" + str(lat) + "<=>" + "x:" + str(x) + "," + "y:" , str(y))
print(str(x) + "," + str(y))
print("xy[%d]: %s"%(len(xy)-1,str(xy[len(xy)-1])))
print("\n")
print("len(xy): %d"%(len(xy)))
polygonCoordinatesInEPSG25832.append(xy)
print("len(polygonCoordinatesInEPSG25832[%d]: %d"%(i,len(polygonCoordinatesInEPSG25832[i])))
xy.clear()
print("len(polygonCoordinatesInEPSG25832 = %d" %(len(polygonCoordinatesInEPSG25832)))
for k in range(len(polygonCoordinatesInEPSG25832)):
for l in range(len(polygonCoordinatesInEPSG25832[k])):
x = polygonCoordinatesInEPSG25832[k][l][0]
y = polygonCoordinatesInEPSG25832[k][l][1]
print(str(x) + ",,,,,,,,,,,,,,,,,,," + str(y))
polygonCoordinatesInEPSG25832 contain values but polygonCoordinatesInEPSG25832[k] don't.
You append it with xy but you didn't unlinked it so when you call xy.clear() it become empty. Try deep copy it instead.

Leading/prefix 0s in out of for loop

I am writing a four loop in my program that writes data to a file. I'm wanting for the output to be formatted as follows
frame001 + K.1
frame002 + K.2
...
frame099 + K.99
frame100 + K.100
So far I am doing
for f in range(1, 100):
file.write('frame' + str(f) + ' + K.' + str(f) + '\n')
I have no problem having the K part come out correctly as K.1-K.100, but I don't know how to have prefix zeros/have it output also frame00F to frameFFF with the appropriate amount of preceding zeros.
Using str.format:
>>> 'frame{0:03d} + K.{0}\n'.format(1)
'frame001 + K.1\n'
>>> 'frame{0:03d} + K.{0}\n'.format(100)
'frame100 + K.100\n'
BTW, range(1, 100) will not yield 100. If you want 100 to be included, that should be range(1, 101).
If you are using old version of Python (Python 2.5-), use % operator (String formatting operator) instead (need to specify multiple argument unlike str.format)
>>> 'frame%03d + K.%d\n' % (1, 1)
'frame001 + K.1\n'
>>> 'frame%03d + K.%d\n' % (100, 100)
'frame100 + K.100\n'
If you don't want to repeat arguments, you can pass mapping instead with slightly different format specifier:
>>> 'frame%(i)03d + K.%(i)d\n' % {'i': 1}
'frame001 + K.1\n'

Organize dictionary by frequency

I create a dictionary for the most used words and get the top ten. I need to sort this for the list, which should be in order. I can't do that without making a list, which I can't use. Here is my code. I am away dictionaries cannot be sorted, but i still need help.
most_used_words = Counter()
zewDict = Counter(most_used_words).most_common(10)
newDict = dict(zewDict)
keys = newDict.keys()
values = newDict.values()
msg = ('Here is your breakdown of your most used words: \n\n'
'Word | Times Used'
'\n:--:|:--:'
'\n' + str(keys[0]).capitalize() + '|' + str(values[0]) +
'\n' + str(keys[1]).capitalize() + '|' + str(values[1]) +
'\n' + str(keys[2]).capitalize() + '|' + str(values[2]) +
'\n' + str(keys[3]).capitalize() + '|' + str(values[3]) +
'\n' + str(keys[4]).capitalize() + '|' + str(values[4]) +
'\n' + str(keys[5]).capitalize() + '|' + str(values[5]) +
'\n' + str(keys[6]).capitalize() + '|' + str(values[6]) +
'\n' + str(keys[7]).capitalize() + '|' + str(values[7]) +
'\n' + str(keys[8]).capitalize() + '|' + str(values[8]) +
'\n' + str(keys[9]).capitalize() + '|' + str(values[9]))
r.send_message(user, 'Most Used Words', msg)
How would I do it so the msg prints the words in order from most used word on the top to least on the bottom with the correct values for the word?
Edit: I know dictionaries cannot be sorted on their own, so can I work around this somehow?
Once you have the values it's as simple as:
print('Word | Times Used')
for e, t in collections.Counter(values).most_common(10):
print("%s|%d" % (e,t))
Print something like:
Word | Times Used
e|4
d|3
a|2
c|2
From the Docs: most_common([n])
Return a list of the n most common elements and their counts from the
most common to the least. If n is not specified, most_common() returns
all elements in the counter. Elements with equal counts are ordered
arbitrarily:
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
Your code can be:
from collections import Counter
c = Counter(most_used_words)
msg = "Here is your breakdown of your most used words:\n\nWords | Times Used\n:--:|:--:\n"
msg += '\n'.join('%s|%s' % (k.capitalize(), v) for (k, v) in c.most_common(10))
r.send_message(user, 'Most Used Words', msg)
import operator
newDict = dict(zewDict)
sorted_newDict = sorted(newDict.iteritems(), key=operator.itemgetter(1))
msg = ''
for key, value in sorted_newDict:
msg.append('\n' + str(key).capitalize() + '|' + str(value))
This will sort by the dictionary values. If you want it in the other order add reverse=True to sorted().

Categories