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

import os

import re

import sys

sys.stdout=open('f1.txt','w')

from collections import Counter

from glob import glob


def removegarbage(text):

    text=re.sub(r'\W+',' ',text)

    text=text.lower()

    return text


folderpath='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的浮点除以零


我该如何纠正?


我需要我的输出格式为:单词,计数,概率


MMMHUHU
浏览 243回答 2
2回答

红颜莎娜

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

森林海

检查路径是否存在。如果是这样,请检查目录是否包含至少1个.txt文件。并将整个for循环移至if块内if num_files:    for word, count in counter.most_common():       ...else:   print "No text files found!"
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python