How to pass if division by zero appears - python

I have a long function to do a NLTK task which also calculates the ratio of several things like sum(adj)/len(words).
Sometimes it´s possible that the words are zero which then occures an error. I tried it with something like this
def nltk_process(dict_bp):
try:
#do all the stuff and then calculate several ratios
verhaeltnis_adj_verb = "Verhältnis ADJ/VERB: " + str(dict.get('ADJ')/dict.get('VERB')) # just an example where sometimes it devides by zero
except:
pass
I use the function in a big for loop to do this on about 800 MySQL tables. It works for the most if I f.e. break the loop after 10 iterations. But then in some of the data it devides by zero which makes everything not work.
So is there any simple solution to this? Why does the try and except not work on my function?
error:
global filtered_sentence_verhaeltnis
ZeroDivisionError: division by zero
filtered_sentence_verhaeltnis = ("Sentence Sentiment gefiltert: " + str(sum(filtered_sentence_sent)/len(filtered_sentence_sent)))
EDIT//
My code looks something like this:
for i in dict_bp.values():
nltk_process(i)
in this nltk_process sometimes it gets the error because of the empty values of the dict. So I need something to make my nltk_process function to not error everything, just keep continueing if an error occures.
Thanks.

thanks for your help.
So I fixed it. I used try and except but not in the function itself. I had to use it in the loop where I call the function.
Now it looks like this:
def export_all_to_excel(dict_bp):
workbook = xlsxwriter.Workbook("Export_ALL.xlsx")
z = 0
worksheet = workbook.add_worksheet('Analyse')
for key,values in dict_bp.items():
z += 1
try:
nltk_einzelauswahl(list(values))
#some more stuff
worksheet.write('G{}'.format(z), sentence_sent_verhaeltnis)
except:
worksheet.write('A{}'.format(z), key)
worksheet.write('B{}'.format(z), "Some error occured")
workbook.close()

Related

Try statement in nested for-loop to bypass errors (syntax error )

I have a data frame with the text entries dataframe['text'] as well as a list of features to compute for the function. Although not all features work for all text entries, so I was trying to compute everything possible, without manually checking which one worked for which entry. So I wanted the loop to continue after the point where it errors:
with Processor('config.yaml', 'en') as doc_proc:
try:
for j in range (0,len(features)):
for i in range (0, len(dataframe['text'])) :
doc = doc_proc.analyze(dataframe['text'][i], 'string')
result = (doc.compute_features([features[j]]))
dataframe.loc[dataframe.index[i], [features[j]]] = list(result.values())
except:
continue
but I got the SyntaxError: unexpected EOF while parsing. The loop without try works, so I understand it's the reason but can't seem to find the correct way to change the syntax
Put the try/except inside the loop. Then it will resume with the next iteration.
with Processor('config.yaml', 'en') as doc_proc:
for feature in features:
for i in range (0, len(dataframe['text'])):
try:
doc = doc_proc.analyze(dataframe['text'][i], 'string')
result = (doc.compute_features([feature]))
dataframe.loc[dataframe.index[i], [feature]] = list(result.values())
except:
pass

Value of string to be a trigger

I'm trying to get my code to get a string of data from a sensor, and then do something when it reads a specific value.
The following code is how I'm receiving the data now (this is just a test) the function is called earlier in the code at the time where I want it to be called.
def gettemperature(self)
temp = self.board.temp_sensor
print("Temperature is " + str(round(temp)) + " degrees.")
This code works, and returns the temperature value rounded to the terminal, but how could I, instead of printing the value to the terminal, make it so when that string of rounded value is say, 200 degrees, then it prints the temperature value? instead of printing it every 2 seconds (the frequency of the data being received, as per another part of the code)
Using something like
if temp = 200
then print(blahblah)
in short, the above code is what I'm trying to do. If the temp equals a certain value, then something else will happen.
That last code doesn't work. I'm pretty new to coding, so I'm assuming I'm either not going about this the right way, or the syntax of how I'm going about trying to get that value to do something isn't correct (obviously)
Thanks for any help! I'm surprised I got this far, haha.
It would be better if your function gettemperature would return something and then print the result in the condition:
def gettemperature()
temp = board.temp_sensor
return temp
temp = gettemperature()
if temp == 200:
print("Temperature is " + str(round(temp)) + " degrees.")
Before using stackoverflow, I'd recommend learning all this stuff from some basic course, as you'll get to learn the stuff yourself rather then get the answer from someone else.
Try learning conditional statements.
what you want is, to put a conditional statement which triggers if temperature is greater than 200.
If the temp is always a number in string data type, you can use the below code.
def gettemperature(self):
temp = self.board.temp_sensor
print("Temperature is " + str(round(temp)) + " degrees.")
temp=int(temp) #typecasting string datatype to integer
if temp == 200:
print("Temperature is high")

How do I run a conditional statement "only once" and every time it changes?

I might be asking a simple question. I have a python program that runs every minute. But I would like a block of code to only run once the condition changes? My code looks like this:
# def shortIndicator():
a = int(indicate_5min.value5)
b = int(indicate_10min.value10)
c = int(indicate_15min.value15)
if a + b + c == 3:
print("Trade posible!")
else:
print("Trade NOT posible!")
# This lets the processor work more than it should.
"""run_once = 0 # This lets the processor work more than it should.
while 1:
if run_once == 0:
shortIndicator()
run_once = 1"""
I've run it without using a function. But then I get an output every minute. I've tried to run it as a function, when I enable the commented code it sort of runs, but also the processing usage is more. If there perhaps a smarter way of doing this?
It's really not clear what you mean, but if you only want to print a notification when the result changes, add another variable to rembember the previous result.
def shortIndicator():
return indicate_5min.value5 and indicate_10min.value10 and indicate_15min.value15
previous = None
while True:
indicator = shortIndicator()
if previous is None or indicator != previous:
if indicator:
print("Trade possible!")
else:
print("Trade NOT possible!")
previous = indicator
# take a break so as not to query too often
time.sleep(60)
Initializing provious to None creates a third state which is only true the first time the while loop executes; by definition, the result cannot be identical to the previous result because there isn't really a previous result the first time.
Perhaps also notice the boolean shorthand inside the function, which is simpler and more idiomatic than converting each value to an int and checking their sum.
I'm guessing the time.sleep is what you were looking for to reduce the load of running this code repeatedly, though that part of the question remains really unclear.
Finally, check the spelling of possible.
If I understand it correctly, you can save previous output to a file, then read it at the beginning of program and print output only if previous output was different.

Is there a way to put multiple lines of code in a try except block and run then sequentially even if one throws an error?

I'm doing some data analysis and creating new columns in a CSV file. Occasionally, as I'm iterating through lines in a pandas dataframe, I get a zero division error. When this happens, I pass to the next line.
Cleaner code:
try:
self.sf1.loc[ind, 'quick'] = (row['assets'] - row['inventory']) / row['liabilities'] # Quick
self.sf1.loc[ind, 'current'] = row['assets'] / row['liabilities'] # Current
self.sf1.loc[ind, 'financial_lev'] = row['debt'] / row['equity'] # Financial Lev
except ZeroDivisionError:
continue
The code above is much easier and cleaner than the other way that functionally works below. The only problem is, if any of the lines of code throw a ZeroDivisionError than none of the other lines of code are run.
Unclean solution:
try:
self.sf1.loc[ind, 'quick'] = (row['assets'] - row['inventory']) / row['liabilities'] # Quick
except ZeroDivisionError:
continue
try:
self.sf1.loc[ind, 'current'] = row['assets'] / row['liabilities'] # Current
except ZeroDivisionError:
continue
try:
self.sf1.loc[ind, 'financial_lev'] = row['debt'] / row['equity'] # Financial Lev
except ZeroDivisionError:
continue
Is there any way to do something more similar to the first code bubble while making sure that every line of code runs even if one above it throws an error? By the way, this try, except block is in a pandas iterrows() loop.
No, there isn't: that's the semantic definition of the try-except scope.
I don't understand your complaint about using multiple PANDAS vectorizations, since both code examples use the same ones. The only difference is the exception handling and continuation.
With your current code, note that if you hit a zero division on row 4, then rows 5-bottom will be untouched.
If you need line-oriented continuation control, then you'll have to perform all of the desired divisions explicitly, checking for the exception on every individual operation, rather than the entire vector as a whole.
Jumping off #Barmar's comment, write a function like the following. Hard to say it's better than what you're doing, but it's closest thing to what you're asking. In general #Prune's answer is exactly right — the semantic definition of try-except requires this kind of verbosity.
def try_except_execution(ind, col1, numerator, denominator):
try:
self.sf1.loc[ind, col1] = numerator / denominator
except ZeroDivisionError:
pass
Then just call it on each case:
try_except_execution(ind, 'quick', (row['assets'] - row['inventory']), row['liabilities'])
try_except_execution(ind, 'current', row['assets'], row['liabilities'])
try_except_execution(ind, 'financial_law', row['debt'] / row['equity'])

Assign variable if list index out of range python error

How to pass a string to a variable if an index error is found? Consider the code:
for l1, l2 in zip(open('file1.list'), open ('file2.list')):
a=fasta1[int(l1)]
b=fasta2[int(l2)]
alignments = pairwise2.align.globalxx(a,b)
top_aln = alignments[0]
aln_a, aln_b, score, begin, end = top_aln
print aln_a+'\n'+aln_b
outfast1 = aln_a
outfast2 = aln_b
A number of these functions must be imported (pairwise2 align),
but the file.lists are single column text files with one sequence id (text and numbers) per line, that are used to extract from the fasta1 and fasta2 text files.
Basically, I want to try: each list command ( a=fasta1[int(l1)]) and if there is no error (the id is in range), do as normal (assign variables a and b for that iteration), but if NOT, assign the 'a' variable some placeholder text like 'GGG':
for l1, l2 in zip(open('file1.list'), open ('file2.list')):
try:
a=fasta1[int(l1)]
except IndexError,e:
a="GGG"
continue
try:
b=fasta2[int(l2)]
except (IndexError):
b="CCC"
continue
This code doesn't quite work (when integrated with above code), which isn't surprising given my lack of python prowess, but I don't quite know why. I actually get no text output, despite the print calls... Am I thinking about this right? If there is NO error in the index, I just want it to go on and do the pairwise alignment (with the first a and b variables) and then print some text to stdout.
Any ideas?
Python's conditional (aka ternary) expressions can one-line this for you. They're often criticized for lack of readability, but I think this example reads well enough.
a = fasta1[int(l1)] if int(l1) < len(fasta1) else "GGG"
You don't need continue, because it will skip that iteration of the loop. Consider the following:
for l1, l2 in zip(open('file1.list'), open ('file2.list')):
a = 'GGG'
b = 'CCC'
try:
a = fasta1[int(l1)]
b = fasta2[int(l2)]
except IndexError:
pass

Categories