how to run on array of string in nested loop in python - python

I try to run this code (small part of my program)
I fixed and added whitespaces and now I get new error, maybe this array does not fit to string?
arrayOfPhotos = ["1.jpg", "2.jpg", "3.jpg", "4.jpg"]
for name in arrayOfPhotos:
detections = detector.detectObjectsFromImage(input_image=arrayOfPhotos[name], output_image_path="holo3-detected.jpg")
for detection in detections:
print(arrayOfPhotos[name], " : ", detection["percentage_probability"])
I get the error:
Traceback (most recent call last):
File "dTEST.py", line 13, in <module>
detections = detector.detectObjectsFromImage(input_image=arrayOfPhotos[name], output_image_path="holo3-detected.jpg")
TypeError: list indices must be integers or slices, not str
Can you help me?

what you probably want is this:
arrayOfPhotos = ["1.jpg", "2.jpg", "3.jpg", "4.jpg"]
for name in arrayOfPhotos:
detections = detector.detectObjectsFromImage(input_image=arrayOfPhotos[name], output_image_path="holo3-detected.jpg")
for detection in detections:
print(arrayOfPhotos[name], " : ", detection["percentage_probability"])
whitespace is important in python, for a statement to be part of a loop it needs to be indented vs the loop (I've added 2 spaces before the lines)
edit: the OP edited the question.
replace input_image=arrayOfPhotos[name] with input_image=name

arrayOfPhotos = ["1.jpg", "2.jpg", "3.jpg", "4.jpg"]
for name in arrayOfPhotos:
detections = detector.detectObjectsFromImage(input_image=name, output_image_path="holo3-detected.jpg")
for detection in detections:
print(name, " : ", detection["percentage_probability"])
The array of photos is a list not a dictionary...

Related

IndexError: List index out of range with glob(), rsplit()

I am trying to execute a python script which is giving me an IndexError. I understood that the rsplit() method failed to split the string. I don't exactly know why it is showing index out of range. Could anyone tell me how to solve this problem ?
code
raw_directory = 'results/'
for name in glob.glob(raw_directory + '*.x*'):
try:
#with open(name) as g:
# pass
print(name)
reaction_mechanism = 'gri30.xml' #'mech.cti'
gas = ct.Solution(reaction_mechanism)
f = ct.CounterflowDiffusionFlame(gas, width=1.)
name_only = name.rsplit('\\',1)[1] #delete directory in filename
file_name = name_only
f.restore(filename=raw_directory + file_name, name='diff1D', loglevel=0)
Output
If I delete the file strain_loop_07.xml, I got the same error with another file.
results/strain_loop_07.xml
Traceback (most recent call last):
File "code.py", line 38, in <module>
name_only = name.rsplit('\\'1)[1] #delete directory in filename
IndexError: list index out of range
If rsplit failed to split the string, it returns an array with only one solution, so the [0] and not [1]
I understood in reply of this post that "name" variable is filled with text like "result/strain_loop_07.xml", so you want to rsplit that, with a line more like
name_only = name.rsplit('/', 1)[1]
So you'll get the "strain_loop_07.xml" element, which is what you probably wanted, because name.resplit('/', 1) return something like
['result', 'strain_loop_07.xml']
By the way, don't hesitate to print your variable midway for debuging, that is often the thing to do, to understand the state of your variable at a specific timing. Here right before your split !

Python interpreter defining variable as tulpe when it's a string?

I found this code on the internet, meant to search through text files in a zipped folder to find matches. I ran it in IDLE to see how it worked.. but I have a problem, and it seems to be this line:
fname = seed + ".txt"
The error message returns this:
Traceback (most recent call last):
File "C:/Users/[name]/AppData/Local/Programs/Python/Python36-32/zip2.py", line 10, in <module>
fname = seed + ".txt"
TypeError: can only concatenate tuple (not "str") to tuple
Here is the code:
import re
from zipfile import *
findnothing = re.compile(r"Next nothing is (\d+)").match
comments = []
z = ZipFile("channel.zip", "r")
seed = "90052"
while True:
fname = seed + ".txt"
comments.append(z.getinfo(fname).comment)
guts = z.read(fname)
m = findnothing(guts.decode('utf-8'))
if m:
seed = m.groups(1)
else:
break
print("".join(comments))
I've searched stackoverflow, and have found nothing similar to my issue. Most of them state that a comma in a variable usually causes the compiler to treat it as a tuple. I don't understand why it is saying seed is a tuple. There is no comma, no parenthesis, or anything else that would define it as a tuple to the Python compiler. How can I fix this?
Thanks in advance
Change m.groups(1) to m.group(1) (singular, not plural). Per the docs at https://docs.python.org/3.6/library/re.html#re.match.groups , group returns a single match but groups returns a tuple of all matches. You are getting the error the second time through the loop, when seed has been replaced by the output of groups, which is a tuple.
First, re.match only matches at the start of the string. Make sure you didn't mean to use re.search instead!
Second, m.groups(1) returns a tuple like ('12345',). Try seed = m.groups(1)[0] instead.

Wordnet synset - strange list index out of range Error

I started working with nltk and I am attempting to generate a function that would allow me to pass in an adjective, extract the first synset from wordnet and print it alongside its antonym. Her is my code:
def placementOperator(wordItem):
wordnet_lemmatizer = WordNetLemmatizer()
placementItem = wordnet_lemmatizer.lemmatize(wordItem,'a')
print("The placementItem is: " + placementItem)
iterationSet = wn.synsets(placementItem, 'a')
if iterationSet[0]:
print(" This is the SS NAME : " + iterationSet[0].name())
for j in iterationSet[0].lemmas():
print(" This is the LEMMAAAA: " + j.name())
if j.antonyms():
print(" This is the RElATIONSHIP " + j.name(), j.antonyms()[0].name())
else: print(" _______> NO ANTONYM!")
else: pass
I am almost there, except that my interpreter throws a 'list out of range' exception. I know that I can't call a list position that doesn't exist and I know that this error occurs when one tries to do so. But since I am explicitly testing for this with if iterationSet[0] I am not sure how I am ending up with the error anyways.
Any advice would be highly appreciated.
Her is the error:
Traceback (most recent call last):
File "C:/Users/Admin/PycharmProjects/momely/associate/associate.py", line 57, in <module> preProcessor(0)
File "C:/Users/Admin/PycharmProjects/momely/associate/associate.py", line 54, in preProcessor placementOperator(each_element[0])
File "C:/Users/Admin/PycharmProjects/momely/associate/associate.py", line 31, in placementOperator if iterationSet[0]:
IndexError: list index out of range
Most likely, wn.synsets(placementItem, 'a') returned you an empty list. This can happen if placementItem isn't in wordnet.
Therefore, when you did iterationSet[0], it throws an out of range exception. Instead, you can change your check to be :
if iterationSet:
print( ....
....
instead of
if iterationSet[0]:
print(...

callig str when using functions

im writing some code to print a triangle with so many rows but when i try it it says,
how many rows in the triangle 5
Traceback (most recent call last):
File "U:\School\Homework\year 8\module 3\IT\python\lesson 10\extention task set by Mr Huckitns.py", line 6, in <module>
triangle(5)
File "U:\School\Homework\year 8\module 3\IT\python\lesson 10\extention task set by Mr Huckitns.py", line 5, in triangle
print((x*(str(" ")))(int(i)*(str("*")))((int(row)-int(i))*(str(" "))))
TypeError: 'str' object is not callable
anybodyknow whats going on here
the code i am using is
inttrow=int(input("how many rows in the triangle "))
def triangle(row):
for i in range(1,row):
x=int(inttrow)-int(i)
print((x*(str(" ")))(int(i)*(str("*")))((int(row)-int(i))*(str(" "))))
triangle(5)
The problem is the punctuation in your print statement. You're printing three strings in succession, but you forgot to put any concatenation operation between them. Try this:
print ((x*(str(" "))) + (int(i)*(str("*"))) + ((int(row)-int(i))*(str(" "))))
Further, why are you doing all these type coercions -- all of those variables already have the proper types. Cut it down to this:
print (x*" " + i*"*" + (row-i)*" ")
You are trying to contatenate strings by placing them near each other in the code like this:
("hello")(" ")("world")
Try that on the command line and see what happens. It is not the syntax of the language you are using. Then try using the plus sign.
"hello" + " " + "world"

Python - Reading binary file with offsets and structs

I've recently gotten back into programming and decided as a project to get me going and motivated I was going to write a character editor for fallout 2. The issue I'm having is after the first few strings I can't seem to pull the data I need using the file offsets or structs.
This is what I am doing.
The file I Am working with is www.retro-gaming-world.com/SAVE.DAT
import struct
savefile = open('SAVE.DAT', 'rb')
try:
test = savefile.read()
finally:
savefile.close()
print 'Header: ' + test[0x00:0x18] # returns the save files header description "'FALLOUT SAVE FILE '"
print "Character Name: " + test[0x1D:0x20+4] Returns the characters name "f1nk"
print "Save game name: " + test[0x3D:0x1E+4] # isn't returning the save name "church" like expected
print "Experience: " + str(struct.unpack('>h', test[0x08:0x04])[0]) # is expected to return the current experience but gives the follosing error
output :
Header: FALLOUT SAVE FILE
Character Name: f1nk
Save game name:
Traceback (most recent call last):
File "test", line 11, in <module>
print "Experience: " + str(struct.unpack('>h', test[0x08:0x04])[0])
struct.error: unpack requires a string argument of length 2
I've confirmed the offsets but it just isn't returning anything as it is expected.
test[0x08:0x04] is an empty string because the end index is smaller than the starting index.
For example, test[0x08:0x0A] would give you two bytes as required by the h code.
The syntax for string slicing is s[start:end] or s[start:end:step]. Link to docs

Categories