为了账号安全,请及时绑定邮箱和手机立即绑定

如何修复python中的零除错误?

如何修复python中的零除错误?

MMMHUHU 2021-03-29 20:09:47
import osimport reimport syssys.stdout=open('f1.txt','w')from collections import Counterfrom glob import globdef removegarbage(text):    text=re.sub(r'\W+',' ',text)    text=text.lower()    return textfolderpath='d:/induvidual-articles'counter=Counter()filepaths = glob(os.path.join(folderpath,'*.txt'))num_files = len(filepaths)with open('topics.txt','r') as filehandle:    lines = filehandle.read()    words = removegarbage(lines).split()   counter.update(words)for word, count in counter.most_common():    probability=count//num_files    print('{}  {} {}'.format(word,count,probability))我得到零除法错误:行概率= count // num_files的浮点除以零我该如何纠正?我需要我的输出格式为:单词,计数,概率
查看完整描述

2 回答

?
红颜莎娜

TA贡献1842条经验 获得超12个赞

您的num_files变量为0。

检查是否folderpath='d:/induvidual-articles'正确(induvidual拼写错误,但原始目录可能类似地拼写错误)。


查看完整回答
反对 回复 2021-04-02
?
森林海

TA贡献2011条经验 获得超2个赞

检查路径是否存在。如果是这样,请检查目录是否包含至少1个.txt文件。并将整个for循环移至if块内



if num_files:

    for word, count in counter.most_common():

       ...

else:

   print "No text files found!"


查看完整回答
反对 回复 2021-04-02
  • 2 回答
  • 0 关注
  • 242 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号