如果出现除零,如何通过

2024-10-02 02:39:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很长的函数来执行NLTK任务,它还计算一些事情的比率,比如sum(adj)/len(words)

有时,单词可能为零,然后出现错误。我用这种东西试过了

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

我在一个大for循环中使用该函数在大约800个MySQL表上执行此操作。如果I.f.e.在10次迭代后打破循环,它的效果最好。但在一些数据中,它的偏差为零,这使得一切都不起作用

有什么简单的解决办法吗?为什么try和except对我的函数不起作用

错误:

global filtered_sentence_verhaeltnis
ZeroDivisionError: division by zero

filtered_sentence_verhaeltnis = ("Sentence Sentiment gefiltert: " + str(sum(filtered_sentence_sent)/len(filtered_sentence_sent)))

编辑//

我的代码如下所示:

for i in dict_bp.values():
        nltk_process(i)

在这个nltk_process中,有时它会因为dict的空值而出错。因此,我需要一些东西使我的nltk_process函数不出错,只要在发生错误时继续

谢谢


Tags: 函数len错误processdictsentencefilteredsum
1条回答
网友
1楼 · 发布于 2024-10-02 02:39:15

谢谢你的帮助

所以我把它修好了。我使用了try and except,但没有在函数本身中使用。我必须在调用函数的循环中使用它

现在看起来是这样的:

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()   

                                                                     

相关问题 更多 >

    热门问题