Multiple image names - python-3.x

I need to save images after cropping that image in a for loop, how can this be achieved?
I have tried using img2.save("img"+i+".png") but this gives an error.
for file in files(path):
if file.endswith('.png'):
img=Image.open(file)
img2 = img.crop((x0,y0,x1,y1))
img2.save("img"+i+".png")
i+=1
The output should be as follows:
1. image1_crop.png
2. image2_crop.png
....

You forgot to post the exact error message but you obviously have a TypeError here:
img2.save("img"+i+".png")
since adding strings and numbers is not allowed (for the obvious reason that it makes no sense at all).
You want to use string formating instead:
img2.save("img{}.png".format(i))

Related

How to account for unexpected data when trying to split values

I have the following code snippet which is part of a larger chunk of code to extract image filenames from links.
for a in soup.find_all('a', href=True):
url = a['href']
path, file = url.rsplit('/', 1)
name, ext = file.rsplit('.', 1)
It works very well, however on occasion the data (which comes from an external source) will have errors.
Specifically, the last line in the snippet above will throw an error that:
name, ext = file.rsplit('.', 1)
ValueError: not enough values to unpack (expected 2, got 1)
What is the best way to ignore this error (or lines containing input not as expected) and continue on to the next entry?
I would have thought a try and catch is the right approach here, but upon googling how to do that with this type of error I did not find anything.
Is it possible to use a try block to catch this type of error? If not, why not, and what is the better approach?
Assuming all you need is to ignore the error, this try/except style should work for you:
for item in ['a.b.c', 'a.b', 'a', 'a.b.c']:
try:
path, file = item.rsplit('.',1)
print("%s, %s" % (path, file))
except ValueError:
print("error with %s" % item)
continue
print("more work here!")
which gives the output:
a.b, c
more work here!
a, b
more work here!
error with a
a.b, c
more work here!
Of course, this may not be the best solution to use, depending on the greater context of what you are trying to do. Is it safe to just ignore the files with no extensions?
In particular, you should generally try to sanitize incoming data as much as possible before processing it, though this is a relatively trivial example and its likely that sanitizing the data for this would be just as expensive as doing this particular split. Put another way, user input being dirty isn't really an "exceptional" condition.
I would not use a try-except in this case, since you have no use for the except part. You're not going to be processing the file if you do encounter an error. Feel free to read up on try-excepts, there are tons of questions on stack overflow about it to see what you think will work best for you.
It sounds like you don't understand the error. The error is because you must have a filename that doesn't have an extension. so when you do rsplit, it only has 1 value. For example:
file = 'babadabooey'
print(file.rsplit('.', 1))
Out: ['babadabooey']
So if you try to unpack that into two values, you're going to get an error. I assume, most of the time you are expecting something like
file = 'babadabooey.exe'
print(file.rsplit('.', 1))
Out: ['babadabooey', '.exe']
So if you try to unpack that value into two values, you're fine. How I would proceed is with an if statement, that way you only try to split it IF '.' is in the file var.
if '.' in file:
name, ext = file.rsplit('.', 1)

Calling a template variable from an output modifier in Modx?

I'm trying to output a template variable inside the if statement in ModX, but it gives no output.
I have multiple pages with links to articles and the point is to only output template variable content on the first page but not the others.
// This gives no output:
[[!#get.page:is=`1`:or:is=``:then=`[[*content]]`:else=``]
// This outputs "yes" on the first page and "no" on others:
[[!#get.page:is=`1`:or:is=``:then=`yes`:else=`no`]]
I've even tried this, but it still does not give any output. I guess the problem is not about the output modifier:
[[!#get.page:is=`1`:or:is=``:then=`[[*content]]`:else=`[[*content]]`]
I'm using ModX Revo 2.7.0
Any help is appreciated, thanks in advance!
Actually in your case missing a double closing angle bracket "]]"
[[!#get.page:is=`1`:or:is=``:then=`[[*content]]`:else=``]]
The `or:is=` is matching against an empty state. Unless that is intentional you should be able to remove it. Also, the `:else=`` is the default state, so, you don't need that either.
The following should work and you'll have cleaner code:
[[!#get.page:is=`1`:then=`[[*content]]`]]

Comparing strings in python 2.7

This is my code:
for films in filmlist:
with codecs.open('peliculas.txt', encoding='utf8', mode='r') as lfile:
filmsDone = lfile.read()
filmsDoneList = filmsDone.split(',')
if films not in filmsDoneList:
with codecs.open('peliculas.txt', encoding='utf8', mode='a+') as lfile:
lfile.write(films.strip() + ',')
It will never recognize the last item of the list.
I have printed filmsDoneList and the last item in PyCharm looks like this: u'X Men.Primera Generacion'. I have printed films and they looks like this: X Men.Primera Generacion'
So I have no idea where is the problem. Thanks in advance.
#Rafa, for you to better understand what I meant in the comments, I had to write an entire answer in order for me to attach codes and screenshots.
Let's say the peliculas.txt file has the following format:
You can import such file in python according the following 3 commands:
fileIN=open('peliculas.txt','r')
filmsDoneList=fileIN.readlines()
fileIN.close()
So you basically open the file, import each line thanks to readlines() and then close the file because its contents are available in filmsDoneList. The latter has the following contents (in PyCharm):
Obviously this list is quite long and does not fit in my screen, but you get the point.
You can now get rid of that annoying newline tag '\r\n' by means of the following loop:
for id in range(len(filmsDoneList)):
filmsDoneList[id]=filmsDoneList[id].strip()
and now filmsDoneList has the form:
much better now, innit?
Now, let's say you want to add the following films:
newFilms=['The Exorcist','Back to the Future','Aliens','Back to the Future']
To make your code more robust, I have added Back to the Future twice. Basically you can get rid of duplicates in newFilms by means of the set() function. This will convert newFilms in a set with duplicates removed, but we will convert it back to a list thanks to this command:
newFilms=list(set(newFilms))
and now newFilms has the form:
Now that everything has been sorted, it's time to check if items in newFilms already are in filmsDoneList which, recall, is the contents of peliculas.txt.
Reopen peliculas.txt as follows:
fileOUT=open('peliculas.txt','a')
the 'a' tag means "append", so basically everything you write will be added to the file without removing anything from it.
And the main loop goes:
for film in newFilms:
if film in filmsDoneList:
pass
else:
fileOUT.write(film+'\n')
the pass means "do nothing". The write commands also appends the newline tag to the movie title: this will keep the previous format of 1 title per line. At the end of this loop you might as well close fileOUT.
The resulting peliculas.txt is
and, as you can see, Back to the Future was in newFilms but wasn't appended to the end of this file because already was in it. As instead, The Exorcist and Aliens have been appended to this file, at the bottom.
If your file has titles separated by commas, this approach is still valid. However you must add
filmsDoneList=filmsDoneList[0].split(',')
after the first for loop. Also in the write function (in the last for loop) you might want to replace the newline value with a comma.
This approach is cleaner, I reckon will also fix the problem you've been having and avoids continuous open/close files in a loop. Hope this helps!

Same for loop, giving out two different results using .write()

this is my first time asking a question so let me know if I am doing something wrong (post wise)
I am trying to create a function that writes into a .txt but i seem to get two very different results between calling it from within a module, and writing the same loop in the shell directly. The code is as follows:
def function(para1, para2): #para1 is a string that i am searching for within para2. para2 is a list of strings
with open("str" + para1 +".txt", 'a'. encoding = 'utf-8') as file:
#opens a file with certain naming convention
n = 0
for word in para2:
if word == para1:
file.write(para2[n-1]+'\n')
print(para2[n-1]) #intentionally included as part of debugging
n+=1
function("targetstr". targettext)
#target str is the phrase I am looking for, targettext is the tokenized text I am
#looking through. this is in the form of a list of strings, that is the output of
#another function, and has already been 'declared' as a variable
when I define this function in the shell, I get the correct words appearing. However, when i call this same function through a module(in the shell), nothing appears in the shell, and the text file shows a bunch of numbers (eg: 's93161), and no new lines.
I have even gone to the extent of including a print statement right after declaration of the function in the module, and commented everything but the print statement, and yet nothing appears in the shell when I call it. However, the numbers still appear in the text file.
I am guessing that there is a problem with how I have defined the parameters or how i cam inputting the parameters when I call the function.
As a reference, here is the desired output:
‘She
Ashley
there
Kitty
Coates
‘Let
let
that
PS: Sorry if this is not very clear as I have very limited knowledge on speaking python
I have found the solution to issue. Turns out that I need to close the shell and restart everything before the compiler recognizes the changes made to the function in the module. Thanks to those who took a look at the issue, and those who tried to help.

Problems using matlab to print a histogram to a file

I am trying to create a histogram of numbers in an array. I am using Matlab to do this. I am connecting via ssh so I can only use Matlab in the terminal on my Linux computer. I am trying to create a histogram of the data in the array and save it as a .png. I know that in order for me to save this I need to use the print function. So far my attempt has been the following:
h=hist(array)
print(h,'-dpng','hist1.png')
which told me that there is no variable defined as -dpng but I thought that the point of that was to specify the file type.
Then I just deleted the -dpng and ran it as
print(h,'hist1.png')
to which it told me "Handle must be scalar, vector, or cell-array of vectors"
At this point I don't quite know what to do next. I would like for someone to help me figure out how to print this histogram to a .png file. Thank you.
hist does not return a figure handle, you could to do something similar to:
h = figure;
hist(array);
print(h, '-dpng', 'hist1.png');
to save the histogram.
By itself, the function hist(array) plots a histogram. If you assign the output to a variable, it returns the binned values of array, not the handle to your plot.
f = figure;
hist(array)
saveas(f,'hist.png')
you may would like to output the array to a csv file.
fid = fopen('file.csv','wt');
for i=1:size(arr)
fprintf(fid, '%s,%d,%d\n','element number' ,i ,arr(i));
end
fclose(fid);
See this link, you should be able to change the answers there to your needs: Outputing cell array to CSV file ( MATLAB )
You don't need to use figure handle unless you want to print not current figure. By default print uses gcf that returns handle for current figure.
So you just can do:
hist(array)
print('-dpng','hist1.png')
You got an error that there is no variable defined as -dpng probably because you forgot one quote symbol and used -dpng'.

Resources